pthesis
pthesis

Reputation: 336

Dynamic options object for jQuery plugin (examples of)

Is anyone aware of any jQuery plugins that can work with a dynamic options object?

What I mean is, I need to be able to pass in:

$('div').somePlugin({title : 'title1', label : function(element){}, etc.});

and also

$('div').somePlugin({name : 'name1', url : function(element){},
                     event : 'event1', etc.});

So the options object needs the ability to have a variable number of items, key names, and values that can either be static or functions. If it's a function, I need to be able to evaluate the function before passing the value back from the plugin.

Upvotes: 3

Views: 932

Answers (2)

cletus
cletus

Reputation: 625037

Use the typeof operator:

jQuery.fn.somePlugin = function(p) {
  if (typeof p == "function") {
    var params = p();
  } else if (typeof p == "object") {
    var params = p;
  } 
  return this.each(function(){
    // use params
  });
};

If you are passed in an object it can have variable properties (name and number) and the values of those can easily be functions, objects, simple values or whatever.

Upvotes: 1

Doug Neiner
Doug Neiner

Reputation: 66191

Two plugins come to mind that use a similar pattern.

  1. I helped write this one, and build the callback navigationFormatter option: AnythingSlider. Notes for how the navigationFormatter option works is in the top of the source file.

  2. The second one is jQuery Autocomplete. The formatItem, formatMatch and formatReturn all use a similar pattern.

Upvotes: 0

Related Questions