13
votes

Has anyone extended an existing jQuery plugin?

I am unsure of where to start. I would rather not actually copy and modify the plugin I wish to extend. Do I do this through prototype or just an extend call on the plugin in question?

Or am I dreaming that it would make sense to do this?

2

2 Answers

10
votes

EDIT: As pointed out by Seb, this is not strictly an example of 'extending' a plugin, more 'encapsulating' a plugin, so take it as it comes :)

Here's something I did to simplify my usage of the jquery autocomplete plugin a while ago:

// small autocomplete plugin wrapping the full autocomplete plugin for a standard look and feel
(function($) {
    $.fn.standardAutocomplete = function(type) {
        return this.autocomplete(ToAbsoluteUrl("~/System/Autocomplete/" + type), {
            formatItem: formatItem,
            formatResult: formatResult
        });
        // Autocomplete formatting callbacks
        function formatItem(row) { return row[0] + "<span class=\"sub\">" + row[1] + "</span>"; }
        function formatResult(row) { return row[0].replace(/(<.+?>)/gi, ''); }
    }
})(jQuery);

Now that's not following "by the book" jquery coding practise - e.g. I'm not accounting for the fact there could be multiple elements selected, but in this case, I know I'm never going to select more than one element on a page with this so I wanted to keep simple, and it "works for me". You might be able to use a similar approach, perhaps with a little more sophistication.

2
votes

If the plugin is well done, then you don't have many alternatives other than using its options to change its behavior.

The purpose of this is that all its code is encapsulated and doesn't interfere with other code, so you can't inject any code in it.

If you really need to change its behavior, then I guess you'll need to copy & paste the code.