Skip to content

Instantly share code, notes, and snippets.

@db
Created February 1, 2011 06:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save db/805516 to your computer and use it in GitHub Desktop.
Save db/805516 to your computer and use it in GitHub Desktop.
advanced jquery plugin pattern
(function($){
var settings, defaults = {
prop1 : 'value1',
prop2 : 'value2'
};
var methods = {
// lifecycle
create: function(options) {
var that = this;
// apply options to default to create settings
settings = (options) ? $.extend({},defaults,options) : defaults;
// bind events (or delegate)
$(window).bind("advancedPlugin.myEvent", function() {
$(that).advancedPlugin("method1");
});
console.log("created!");
// initialise plugin
return this.each(function(index, element){
var $this = $(this), data = $this.data("advancedPlugin");
// data binding on each item
if (!data) $(this).data("advancedPlugin",{count:0});
// other inits to follow
});
},
destroy: function() {
// unbind events
$(window).unbind(".advancedPlugin");
// unbind data
$(this).removeData("advancedPlugin");
// undo any inits if required
console.log("destoyed!");
},
// methods
method1: function() {
console.log("method1!");
return $(this).each(function(index, element){
console.log($(this).data("advancedPlugin"));
var data = $(this).data("advancedPlugin");
data.count++;
$(this).data("advancedPlugin",data);
});
},
method2: function() {
var nochain = null;
$(window).trigger("advancedPlugin.myEvent");
console.log("method2!" );
return nochain;
}
};
$.fn.advancedPlugin = function(method) {
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
}
if ( typeof method === "object" || ! method ) {
return methods.create.apply( this, arguments );
}
$.error("Method " + method + " does not exist on jQuery.advancedPlugin");
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment