2

I'm using a jQuery plugin that has its functions defined as such:

 $('#mydiv').pluginAction({
 someproperty: val, 
 format: 'mm hh',
 labels: ['yes', 'no', 'maybe'], 
 labels1: ['never', 'always']
 });

In my HTML page, I have multiple DIVs that have the same properties for format, labels, labels1, but different values for someproperty. Is there some type of JavaScript notation I can take advantage of to shorten the definition so that I don't have to have duplicate code?

asked Apr 11, 2010 at 7:20
1
  • 1
    Some plugins allow you to send an object literal to replace the defaults for the plugin. You could use this for you values that dont change. Commented Apr 11, 2010 at 9:02

3 Answers 3

6

There are a couple of ways of dealing with this:

  1. Create a function which fills in the blanks; or

  2. If the plugin is yours, default those values to what you want.

Example of (1):

function props(val) {
 return {
 someproperty: val,
 format: 'mm hh',
 labels: ['yes', 'no', 'maybe'], 
 labels1: ['never', 'always']
 };
}
$("#mydiv").pluginAction(props("..."));
answered Apr 11, 2010 at 7:28
Sign up to request clarification or add additional context in comments.

Comments

4

Cletus has a very good answer, which allows you to produce very readable code. This is probably the best solution in your case.

Just for the record, something like the following would also be possible. You could create an object literal storing all fixed properties, and then just specify add extra properties (such as someProperty in your example) when needed by using jQuery#extend.

var props = {
 format: 'mm hh',
 labels: ['yes', 'no', 'maybe'], 
 labels1: ['never', 'always']
};
$('#mydiv').pluginAction($.extend(props, { someProperty: val }));
answered Apr 11, 2010 at 7:42

Comments

1

There's nothing wrong with duplicating that sort of code. It actually makes it clear what sort of behavior applies on that given div. If however you're talking of hundreds of duplications, use what other people have suggested.

answered Apr 11, 2010 at 7:54

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.