jQuery ボイラープレート サイトから、次のようなプラグインを思いつきました。
;(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);
したがって、次のように使用できます
$('.stuff').myPlugin({abc: 5});
次のように、パブリック メソッドの呼び出しも許可するにはどうすればよいですか。
$('.stuff').myPlugin('goTo', 'top');
// should call instance.goTo('top');
または:
$('.stuff').myPlugin('close');
// should call instance.close();
?
$.fn.myPlugin 関数宣言に変数を追加して、オプションが文字列の場合は if ステートメントで確認することで可能であることはわかっていますが、これを行うためのより良い方法があるかどうか疑問に思っていました
たとえば、PHP では次のようになります。
$args = func_get_args();
$arg1 = array_shift($args);
return call_user_func_array(array($this, $arg1), $args);
javascriptでこれを行うにはどうすればよいですか?