jQuery插件:添加回调功能

dcl*_*901 84 jquery function callback

我正在尝试提供我的插件回调功能,我希望它以一种传统的方式运行:

myPlugin({options}, function() {
    /* code to execute */
});
Run Code Online (Sandbox Code Playgroud)

要么

myPlugin({options}, anotherFunction());
Run Code Online (Sandbox Code Playgroud)

如何在代码中处理该参数?它被视为一个完整的实体吗?我很确定我知道在哪里放置执行代码,但是如何让代码执行?我似乎无法找到很多关于这个主题的文献.

Dav*_*ing 164

只需在插件中执行回调:

$.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
    }
};
Run Code Online (Sandbox Code Playgroud)

您还可以在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);

};
Run Code Online (Sandbox Code Playgroud)

像这样使用它:

$('.elem').myPlugin({
    callback: function() {
        // some action
    }
});
Run Code Online (Sandbox Code Playgroud)

  • @JeaffreyGilbert你应该带上jQuery上下文,我会做`options.callback.call(this,param);` (2认同)

Fel*_*ing 5

我不知道我是否理解你的问题.但对于第二个版本:这将anotherFunction立即打电话.

基本上你的插件应该是某种看起来像这样的函数:

var myPlugin = function(options, callback) {
    //do something with options here
    //call callback
    if(callback) callback();
} 
Run Code Online (Sandbox Code Playgroud)

你必须提供一个函数对象作为回调,所以要么是(function(){...}anotherFunction没有()).