Best Way to Extend a jQuery Plugin

justkt picture justkt · Jan 12, 2010 · Viewed 61.5k times · Source

I'm a fairly new jQuery user looking to extend an existing jQuery plugin that does about 75% of what I need. I've tried to do my homework on this. I've checked out the following questions on stackoverflow:

I've read up on the extend method. However, all of thise homework has left me confused. I'm working with the fullcalendar plugin and need to modify some of the behavior as well as add new event hooks. Am I stuck with doing this in the plugin closure itself? Am I missing something obvious?

Ideally we would be able to separate our code from the plugin code to allow for a possible upgrade. Any help would be greatly appreciated, especially pointers on where I'm missing some information or opinions on whether the solutions already presented in other Stack Overflow questions make sense. To me they contradict each other and I'm still left confused.

Answer

Jared Scott picture Jared Scott · Dec 11, 2010

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.