jQuery插件:添加回调功能 [英] jQuery Plugin: Adding Callback functionality

查看:149
本文介绍了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, so thanks in advance for your help.

推荐答案

只要执行插件中的回调:

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对象中使用回调:

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插件:添加回调功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆