views:

107

answers:

2

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.

I realize it's hard for you guys to really help without further specifics, which is why I thought I should see if I can learn from any examples there might already be out there of something like this.

Thanks.

+1  A: 

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.

cletus
In my situation p is an object that contains properties that are both objects and functions, so would I iterate over p using $.each?
pthesis
You could do but your question isn't really specific enough for me to understand what you're trying to do exactly.
cletus
I'm working on a jQuery plugin for Woopra. I think I've got the problem fixed. I really appreciate your help!
pthesis
A: 

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.

Doug Neiner
Thanks Doug. I'm looking at both of those plugins.
pthesis