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.

2
  • 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: stackoverflow.com/questions/1897553/… was correctly answered by @cletus and should be accepted. Just trying to help you out :) Welcome to SO by the way! Commented Dec 14, 2009 at 4:19
  • Didn't realize that, thanks for telling me! Got it done, and thanks for the welcome. I look forward to contributing soon! Commented Dec 14, 2009 at 4:20

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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

1 Comment

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

Your Answer

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.