Created
February 1, 2011 06:49
-
-
Save db/805516 to your computer and use it in GitHub Desktop.
advanced jquery plugin pattern
This file contains 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($){ | |
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