如何向jQuery插件添加标准API功能

时间:2013-08-13 09:19:06

标签: javascript jquery api jquery-plugins

在我创建的jQuery插件中,要从插件外部访问其方法,我必须执行类似

的操作

$("#testItem").data('pluginName').foo_public_method()

但是,我看到其他插件提供了

的API

$('#testItem').pluginName('foo_public_method')

如何启用此类功能?

jsFiddle

1 个答案:

答案 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
    }
}