我正在try 赋予我的插件回调功能,我希望它能以一种有点传统的方式运行:

myPlugin({options}, function() {
    /* code to execute */
});

myPlugin({options}, anotherFunction());

How do I handle that parameter in the code? Is it treated as one full entity? I'm pretty sure I know where I'd place the execut或y code, but how do I get the code to execute? I can't seem to find a lot of literature on the topic.

推荐答案

Just execute the callback in the plugin:

$.fn.myPlugin = function(options, callback) {
    if (typeof callback == 'function') { // make sure the callback is a function
        callback.call(this); // brings the scope to the callback
    }
};

您还可以在options对象中使用回调:

$.fn.myPlugin = function() {

    // extend the options from pre-defined values:
    var options = $.extend({
        callback: function() {}
    }, arguments[0] || {});

    // call the callback and apply the scope:
    options.callback.call(this);

};

Use it like this:

$('.elem').myPlugin({
    callback: function() {
        // some action
    }
});

Jquery相关问答推荐

使用jquery ui来回滑动切换

如何定位 prism.js 脚本中包含的代码?

formData.append 来自不同输入文件的两个文件

更改高亮 colored颜色

jQuery 的元素或类 LIKE Select 器?

将一个类动态添加到 Bootstrap 的popover容器中

Bootstrap 3 RC 1 中的 typeahead JavaScript 模块在哪里?

为什么要两次声明 jQuery?

ajax调用后jQuery点击功能不起作用?

jQuery 插件:添加回调功能

Jquery Ajax 错误处理忽略中止

测试空 jQuery Select 结果

如何使用 jQuery 或纯 JS 重置所有复选框?

jQuery ajax 成功回调函数定义

图片转Base64

单击时平滑滚动到特定的 div

jQuery或javascript查找页面的内存使用情况

在 jquery 中使用 AJAX Post 从强类型 MVC3 视图传递模型的正确方法

jQuery .each() 索引?

catch forEach 最后一次迭代