3

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
pthesis
  • 336
  • 3
  • 16
  • 1
    Its best to start of here on StackOverflow with your best foot forward. The best way to do that is by marking answers as "accepted" by clicking the green check next to the answer. The question you asked earlier: http://stackoverflow.com/questions/1897553/jquery-iterate-over-object-with-each was correctly answered by @cletus and should be accepted. Just trying to help you out :) Welcome to SO by the way! – Doug Neiner Dec 14 '09 at 04:19
  • Didn't realize that, thanks for telling me! Got it done, and thanks for the welcome. I look forward to contributing soon! – pthesis Dec 14 '09 at 04:20

2 Answers2

1

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
  • 616,129
  • 168
  • 910
  • 942
  • 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 Dec 14 '09 at 04:54
  • You could do but your question isn't really specific enough for me to understand what you're trying to do exactly. – cletus Dec 14 '09 at 06:52
  • I'm working on a jQuery plugin for Woopra. I think I've got the problem fixed. I really appreciate your help! – pthesis Dec 14 '09 at 15:07
0

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
  • 65,509
  • 13
  • 109
  • 118