本文介绍了jQuery 插件:添加回调功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to give my plugin callback functionality, and I'd like for it to operate in a somewhat traditional way:

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 executory 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
    }
};

您也可以在选项对象中设置回调:

You can also have the callback in the options object:

$.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);

};

像这样使用它:

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

这篇关于jQuery 插件:添加回调功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 07:34