I have a basic plugin written according the jQuery authoring guide. This plugin implements some basic features for a ul
of elements (activate
, deactivate
and search
).
jquery.myplugin.core.js
(function($) {
var methods = {
init : function(opts){
var options = $.extend({}, $.fn.list.defaults, opts);
return this.each(function(i) {
...
methods.search("my search query"));
});
},
deactivate : function(){ ... },
activate : function(){ ... },
search : function(query){ ... },
};
$.fn.list = function(method){
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.list' );
}
};
$.fn.list.defaults = {...};
})(jQuery);
I have numerous lists in my app, each performing different actions - some sharing features. For example; two lists might be considered deleteable such that items can be deleted from them. Is there a way to write these extra feature sets as mixins or extended plugins of a core plugin?
So I would have:
- jquery.myplugin.core.js
- jquery.myplugin.editable.js
- jquery.myplugin.deletable.js
- ...
I had a look at Best Way to Extend a jQuery Plugin which made me think of:
jquery.myplugin.deletable.js
(function($) {
var extensionMethods = {
delete : function(elem){ console.log("deleting "+elem); }
};
$.fn.list.deletable = function(){ return $.extend(true, $.fn.list.prototype, extensionMethods); };
})(jQuery);
Which I thought would allow me to do:
>>> $('#list').list.deletable();
>>> $('#list').list.deletable("delete", elem);
>>> $('#list').list.deleteable("search", "some element"); # Method from core
but nothing happens as I'm sure there is something I'm not understanding correctly. Can anyone help me out here?