Jquery options with default settings and multiple instances

I created the jQuery plugin and it works very well. Unless I have multiple instances on the same page, the parameters / parameters of the last instance are used for both.

Here's a stripped down version of this ... 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 am sure this is some kind of namespace problem, they confuse me so often.

thank

+5
source share
1 answer

using

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.

, ( ) $.extend(). , , , .

, .data()

: http://jsfiddle.net/roberkules/XvKs8/

+6

All Articles