在我创建的jQuery插件中,要从插件外部访问其方法,我必须执行类似
的操作 $("#testItem").data('pluginName').foo_public_method()
但是,我看到其他插件提供了
的API $('#testItem').pluginName('foo_public_method')
如何启用此类功能?
答案 0 :(得分:1)
您需要查询传递给插件实例的参数,并检查插件是否已在元素上实例化。
从您的示例的外观来看,插件实例存储在元素的data
属性中,因此这应该很容易检查。然后,您可以使用arguments
关键字访问已传入的任何内容。
在下面的代码中,我将this
作为调用该插件的单个元素。
var instance = $(this).data('pluginname');
var args = $.makeArray(arguments);
if (!instance) {
// create the plugin on the element using args as an object
}
else {
// plugin already exists
if (typeof args[0] == "string") {
// arg0 = property
// arg1 = value
}
else {
// logic for passing in arguments as an object
}
}