Created
November 17, 2010 01:43
-
-
Save kflorence/702866 to your computer and use it in GitHub Desktop.
jQuery plugin pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function($) { | |
// $.widget-lite | |
$.plugin = function(name, base, prototype) { | |
if (!prototype) { | |
prototype = base; | |
base = function(options, element) { | |
if (arguments.length) { | |
$.data(element, name, this); | |
this.element = $(element); | |
this._init(options); | |
} | |
}; | |
base.prototype = { | |
_init: function() {} | |
}; | |
} | |
$.extend(true, base.prototype, prototype); | |
$.fn[name] = function(options) { | |
var isMethodCall = (typeof options === "string"), | |
args = Array.prototype.slice.call(arguments, 1), | |
returnValue = this; // Chain by default | |
if (isMethodCall) { | |
if (options.charAt(0) === "_") { // Psuedo-private | |
return returnValue; | |
} | |
this.each(function() { | |
var instance = $.data(this, name) || new base({}, this); | |
if (instance && $.isFunction(instance[options])) { | |
var methodValue = instance[options].apply(instance, args); | |
if (methodValue !== undefined) { | |
returnValue = methodValue; | |
return false; | |
} | |
} | |
}); | |
} else { | |
this.each(function() { | |
var instance = $.data(this, name); | |
if (instance) { | |
instance._init(options); | |
} else { | |
new base(options, this); | |
} | |
}); | |
} | |
return returnValue; | |
}; | |
}; | |
})(jQuery); | |
// Set up like so: | |
jQuery(function($) { | |
$.plugin("pluginName", { | |
options: { | |
test: true | |
}, | |
_init: function(options) { | |
$.extend(true, this.options, options || {}); | |
}, | |
somePublicFunc: function() { | |
console.log(this.options.test); | |
} | |
}); | |
}); | |
// Then use like so: | |
$("#element").pluginName({test: false}); // initialize first | |
$("#element").pluginName("somePublicFunc"); // => false | |
// Or use without initializing (danger!?) | |
$("#element").pluginName("somePublicFunc"); // => true |
Stuck what I've got now in a Repo: https://github.com/kflorence/jquery-plugin
Feel free to tweak
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://jsfiddle.net/kflorence/bc8Kx/ -- Not sure how accurate that benchmark is, but it seems that prototypical inheritance is definitely the way to go. There are definitely other differences in the two plugins, but that one probably has the most bearing on speed ("new" vs. $.extend({}, {...}) is my guess).