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?

+2


source to share


3 answers


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("..."));

      

+6


source


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 }));

      

+4


source


There is nothing wrong with duplicating code like this. It actually makes it clear what behavior is being applied to a given div. If, however, you are talking about hundreds of duplicates, use what other people have suggested.

+1


source







All Articles