Patching Milans jQuery Plugin Pattern for jQuery 1.6

I recently wrote some code with Milan Adamovsky’s jQuery plugin pattern. A nice pattern for writing plugins that does a lot of cool stuff for you.

However, I discovered that with a jQuery version higher than 1.4 everything broke. I could no longer use jQuery at all if the plugin was loaded. I got the very suspect error:
Uncaught TypeError: Cannot call method 'find' of undefined in jquery.min.js:16

After some digging I found out that what the pattern does is to extend jQuerys init method like this:

$.fn.extend({
  init: function (selector, context) {
    return jQuery.fn._plugin = new jQuery.fn.jQueryInit(selector, context);
  }
});

The problem is that jQuery changed the method signature for the init method from this:
init: function( selector, context ) {

to this:
init: function( selector, context, rootjQuery ) {

The solution is to patch the pattern so it gives init all it’s arguments and everything is fine:

$.fn.extend({
  init: function (selector, context, rootjQuery) {
    return jQuery.fn._plugin = new jQuery.fn.jQueryInit(selector, context, rootjQuery);
  }
});

The best thing is that this patch actually works for jQuery 1.4 as well since javascript silently ignores extra arguments.

Ludvig Widman
Posted:
Jun 29, 06:53 PM
Tags:

Comment

Commenting is closed for this article.