What is the best jQuery pattern for the following purposes?
-
Multiple instance of plugin in one page or common selector to send
$(".class").myplugin();
-
Custom accessible method to invoke from outside :
$("#ID").myplugin("command");
I read several articles and eventually got this pattern:
Sample on Fiddle
Making Instance
$.fn.extend({
myplugin: function(options) {
if (!options || typeof(options) == 'object') {
opt = $.extend({}, $.fn.myPlugin.defaults, options);
}
this.each(function() {
new $(this).myPlugin(options);
});
return;
}
});
Define accessible methods
$.fn.myPlugin = function(methodOrOptions) {
var method = {
init: function() {
},
command: function() {
}
};
if (method[methodOrOptions]) {
return method[methodOrOptions].apply(this,Array.prototype.slice.call(arguments, 1));
}
else if (typeof methodOrOptions === 'object' || !methodOrOptions) {
return method.init.apply(this, arguments);
}
else {
$.error('method ' + methodOrOptions + 'not exist . . . :( . . .');
}
};
Now, I want to know the real solution, is my pattern wrong?
I am looking for the best pattern...
Aucun commentaire:
Enregistrer un commentaire