From the jQuery boilerplate site, I've came up with a plugin that looks like this:
;(function($, window, document, undefined){
"use strict";
var defaults = {
abc: 1,
def: 'xyz'
};
function Plugin(element, options){
this.options = $.extend({}, defaults, options, element.dataset);
this.element = element;
}
plugin.prototype = {
goTo: function(where){
// ...
},
close: function(){
$(this.element).removeData('_myplug');
}
};
$.fn.myPlugin = function(options){
return this.each(function(){
if(!$.data(this, '_myplug'))
$.data(this, '_myplug', new Plugin(this, options));
if($.isPlainObject(options))
return;
// here how to check if 'options' matches one of the
// functions, then call it with the rest of the variables
});
};
})(jQuery, window, document);
So it can be used like
$('.stuff').myPlugin({abc: 5});
How can I also allow calls to public methods, like this:
$('.stuff').myPlugin('goTo', 'top');
// should call instance.goTo('top');
Or:
$('.stuff').myPlugin('close');
// should call instance.close();
?
I know it's possible by adding more variables in the $.fn.myPlugin function declaration, then check with an if statement if options is a string, but I was wondering if there's a nicer way to do this
For example, in PHP it would look like this:
$args = func_get_args();
$arg1 = array_shift($args);
return call_user_func_array(array($this, $arg1), $args);
How can I do this in javascript?