Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery plugin not merging defaults with options

I have created my own jquery plugin. It is setup like so.

;(function ($)
{
    $.fn.bpeditor = function (options)
    {
        return this.each(function() 
        {
            // Merge passed options with defaults
            vars.options = $.extend({}, $.fn.bpeditor.defaults, options);

            alert(vars.options.test);
         }
     }

     var vars =
     {
         options: null
     };

     $.bpeditor.defaults =
     {
         user: 'a',
         dkey: 'b',
         side: 'c',
         test: 'd'
     };

})(jQuery);

I call it like so:

$('div#canvas').bpeditor
({
    user: 'user1',
    dkey: 'dkey1'
});

As you can see, I am passing in the 'user', and 'dkey' options but not 'test'. Test has a default value and it's not being set in the plugin. The alert in the plugin should display the contents of vars.options.test which should be filled with the contents of $.bpeditor.defaults but it's coming back as undefined.

Can anyone help?

Thanks

like image 290
tmutton Avatar asked Mar 08 '26 07:03

tmutton


1 Answers

You forgot a .fn.

$.fn.bpeditor.defaults = {
    ...
};

NB: it's unusual to expose your default options so that they can be modified outside of the plugin.

It's more common for them to be a lexically scoped variable that only the plugin can access. There's also no need to recreate the options variable inside the .each loop - all of these affected elements should be sharing the same option state:

(function($) {

    // only created once, shared between all instances
    var defaults = {
        ...
    };

    $.fn.bpeditor = function (options) {
        options = $.extend(true, {}, defaults, options);
        return this.each(function() {
            alert(vars.options.test);
        });
    };
})(jQuery);

The $.extend() line deep copies the defaults and then the supplied options into a new empty object, re-using the options variable - ensuring that the defaults object remains constant and that the passed object isn't modified.

like image 76
Alnitak Avatar answered Mar 09 '26 20:03

Alnitak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!