Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created April 11, 2010 03:52
Show Gist options
  • Save cowboy/362482 to your computer and use it in GitHub Desktop.
Save cowboy/362482 to your computer and use it in GitHub Desktop.
stateful jQuery widget pattern idea
// Rough "widget factory" pattern idea. Maybe dumb, but I'm just fooling
// around at the moment.
(function($,undefined){
'$:nomunge'; // Used by YUI compressor.
var widget_name = 'myWidget',
default_method = 'init',
default_data = {};
$.fn[ widget_name ] = function( method_arg ) {
var args = arguments,
method,
self = {},
result;
function init_data( elem, options ) {
var data;
elem.data( widget_name, data = elem.data( widget_name ) || default_data );
if ( options ) {
data.options = $.extend( data.options, options );
}
return data;
};
self.init = function( options ) {
var data = init_data( this, options );
// other init
};
self.destroy = function() {
// other cleanup
this.removeData( widget_name );
};
// other methods
// Parse arguments.
if ( typeof method_arg === 'string' && self[ method_arg ] ) {
args = Array.prototype.slice.call( args, 1 );
method = method_arg;
}
// Call the appropriate method in the context of each passed element.
// If something is returned, return that instead of the default "initial
// jQuery object" (Beware, this may break the chain)
this.each(function(){
result = self[ method || default_method ].apply( this, args );
});
return result !== undefined ? result : this;
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment