JavaScript / jQuery short function definitions
I am using jQuery plugin which has its functions defined as such:
$('#mydiv').pluginAction({
someproperty: val,
format: 'mm hh',
labels: ['yes', 'no', 'maybe'],
labels1: ['never', 'always']
});
On my HTML page, I have a few the DIV, which have the same properties format
, labels
, labels1
but different values someproperty
. Is there some type of JavaScript notation I can use to shorten the definition so that I don't have duplicate code?
source to share
There are several ways to deal with this:
-
Create a function that fills in the blanks; or
-
If the plugin belongs to you, by default these values are what you want.
Example (1):
function props(val) {
return {
someproperty: val,
format: 'mm hh',
labels: ['yes', 'no', 'maybe'],
labels1: ['never', 'always']
};
}
$("#mydiv").pluginAction(props("..."));
source to share
Cletus has a very good answer that allows for very readable code. This is probably the best solution in your case.
Just for the record, something like the following is possible. You can create an object literal that holds all the fixed properties and then just specify additional properties (like someProperty
in your example) when needed using jQuery#extend
.
var props = {
format: 'mm hh',
labels: ['yes', 'no', 'maybe'],
labels1: ['never', 'always']
};
$('#mydiv').pluginAction($.extend(props, { someProperty: val }));
source to share