Best Way to Extend a jQuery Plugin

Solution 1:

I just had the same problem trying to extend jquery UI plugins, and here is the solution I found (found it through jquery.ui.widget.js):


(function($) {
/**
 *  Namespace: the namespace the plugin is located under
 *  pluginName: the name of the plugin
 */
    var extensionMethods = {
        /*
         * retrieve the id of the element
         * this is some context within the existing plugin
         */
        showId: function(){
            return this.element[0].id;
        }
    };

    $.extend(true, $[ Namespace ][ pluginName ].prototype, extensionMethods);


})(jQuery);

hope this helps, please ask if you have any questions.

Solution 2:

I had the same issue and came here, then Jared Scott's answer inspired me.

(function($) {

    var fullCalendarOrg = $.fn.fullCalendar;

    $.fn.fullCalendar = function(options) {
        if(typeof options === "object") {
            options = $.extend(true, options, {
                // locale
                isRTL: false,
                firstDay: 1,
                // some more options
            });
        }

        var args = Array.prototype.slice.call(arguments,0);
        return fullCalendarOrg.apply(this, args);
    }

})(jQuery);

Solution 3:

Ive found that with a lot of plugins the methods are protected/private (ie in the closures scope). If yo need to modify the functionality of the methods/functions then your out of luck unless youre willing to fork it. Now if you dont need to change any of these methods/functions then you can use $.extend($.fn.pluginName, {/*your methods/properties*/};

Another thing ive ended up doing before is simply using the plugin as a property of my plugin instead of trying to extend it.

What it all really comes down to is how the plugin you want to extend is coded.