1

I have a JQuery 1.4.2 plugin, that uses a set of options. It's pseudo code is like this:

 (function($) {
  // Shell for the plugin code
  $.fn.myPlugIn = function(options) {
    // Plugin code
    return this.each(function() {
      // for each item in selector
      options = $.extend($.fn.myPlugIn.defaults, options);
      ...do stuff
    });
    $.fn.myPlugIn.defaults = {
    header      :   null,
    position    :   'absolute',
    top         :   null,
    left        :   null,
    forinput    :   null,
    forAnchor   :   null,
    sAjaxSource :   null,
    onClick     :   null
  };
  })(jQuery);

When calling the plugin for several elements on a single page, the options are not unique -- the previous elements options are still in the options.

$(document).ready(function() {
    $("#div1").myPlugIn(
            {forinput: "input1",
             onClick: function(data){
                ... do stuff
            },
    });
    $("#div2").myPlugIn({
          forAnchor: "link1",
            onClick: function(data){
                ... do stuff
             },
        header: "Parts"
    });

});

What am I doing wrong? I expected that each time the plugin was found, it would use the options passed to it. Instead, it uses retains all the options from the first instance and overwrites any re-initialized properties from the second instance.

Any replies are appreciated. Thanks in advance for reading my post.

2 Answers 2

4

You need to merge the options into a new object for that instance, like this:

options = $.extend({}, $.fn.myPlugIn.defaults, options);

$.extend() merges into the first argument all objects passed as parameters after that, so currently they're merging into your $.fn.myPlugIn.defaults defaults, leaving it tainted for the next use. Instead you want to never mess with the defaults (unless intentionally changing them elsewhere) and merge the options and defaults into another new object.

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

Comments

1

second thing would be adding 'var options = ...' , omitting var makes it global variable, those setting options to last called attributes.

1 Comment

It won't be a global variable here, since it's a parameter to the function.

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.