Extending objects with JQuery.extend

You have developed a plugin and need to provide default options allowing end users to overwrite them. The solution is simple wink

(function($) {
   $.fn.myPlugin = function(options) {
        options = $.extend({
            message: 'Hello world',
            css: {
                color: 'red'
            }
        }, options);
        return this.each(function() {
            $(this).css(options.css).html(options.message);
        });
    };
})(jQuery);
 

In this recipe, we use the $.extend() method provided by jQuery. $.extend() will return a reference to the first object passed in with the latter objects overwriting any properties they define.

$.extend() also provides a facility for a deep (or recursive) copy. This is accomplished by passing in Boolean true as the first parameter.


 

Posted on: 14/11/2011








0 Comments
If you want to leave a comment please Login or Register