【发布时间】:2013-06-06 13:49:17
【问题描述】:
从jQuery boilerplate site,我想出了一个如下所示的插件:
;(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 语句检查 options 是否为字符串,但我想知道是否有更好的方法来做到这一点
例如,在 PHP 中它看起来像这样:
$args = func_get_args();
$arg1 = array_shift($args);
return call_user_func_array(array($this, $arg1), $args);
如何在 javascript 中做到这一点?
【问题讨论】:
-
也许使用
arguments对象?您仍然需要有一些方法来区分函数的调用方式,这通常是通过检查参数类型和/或某些参数上可能存在的属性。
标签: javascript jquery function object jquery-plugins