Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery settings with default and multiple instances

I've made a jQuery plugin and it works pretty much ok. Except that when I have multiple instances on the same page the last instance's options/settings are used for both.

Here's a stripped down version of it... sorry for the length.

(function() {

    var settings = {};
    var defaults = {
        duration : 1000,
        easingShow : 'easeOutBounce',
        easingHide : 'easeOutQuad'
    };

    var methods = {
        init : function(options) {

            return this.each(function(n) {

                settings = $.extend(defaults, options);

            });

        },

        show : function() {

            // settings used here
        },

        hide : function() {
            // also used here
        }
    };

    $.fn.expander = function(method) {

        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.expander');
        }

    };

})(jQuery);

I'm sure it's some kind of namespace issue, as I get confused by that often.

Thanks

like image 780
ianbarker Avatar asked May 27 '11 16:05

ianbarker


1 Answers

use

settings = $.extend(true, {}, defaults, options);

from jquery docs @ http://api.jquery.com/jQuery.extend/

deep     If true, the merge becomes recursive (aka. deep copy).
target   The object to extend. It will receive the new properties.
object1  An object containing additional properties to merge in.
objectN  Additional objects containing properties to merge in.

Keep in mind that the target object (first argument) will be modified, and will also be returned from $.extend(). If, however, we want to preserve both of the original objects, we can do so by passing an empty object as the target.

To have different settings per element, you can store them at each element using .data()

Check out a working demo: http://jsfiddle.net/roberkules/XvKs8/

like image 172
roberkules Avatar answered Nov 15 '22 04:11

roberkules