回调函数到jQuery插件 [英] Callback function to jQuery plugin

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

问题描述

我怀疑Javascript中的调用函数。我有这个jQuery插件:

I doubt about the "call" function in Javascript. I have this jQuery plugin:

(function($) {
    var methods = {
        method1 : function( settings, callback ) { 
            // do stuff
                if($.isFunction(callback)){
                    callback.call(this, $(list));
                }
        },

        method2 : function( settings, callback ) { 
            // do stuff
                if($.isFunction(callback)){
                    callback.call(this, $(list));
                }
        },

        method3 : function( settings, callback ) { 
            // do stuff
                if($.isFunction(callback)){
                    callback.call(this, $(list));
                }
        },


};

$.fn.jPlugin = function( method ) {
    if ( methods[method] ) {
        return methods[method].apply( this, Array.prototype.slice.call(arguments, 1));
    } 

    else if ( typeof method === 'object') {
        $.error( 'Expected two (2) parameters: parameter 1 must be the method name to call. Parameter 2 must be an object containing the settings for this method.' );
    } 

    else {
        $.error( 'Method ' +  method + ' does not exist' );
    }   
}; 

我对jQuery插件文档中的这行感到困惑:

And I'm a bit confused about this line in the jQuery plugin documentation:

return methods[method].apply( this, Array.prototype.slice.call(arguments, 1));

插件按预期工作id无回调传递。但是如果我像这样调用插件,我该如何将回调传递给正确的方法?

The plugin works as expected id no callback is passed. But how should I do to pass the callback to the correct method if I call the plugin like this?

$('#my-div').jPlugin('method1', settings);

回调函数应该是设置对象的一部分还是我可以调整插件接受这个? / p>

Should the callback function be part of the settings object or might I adapt the plugin to accept this?

$('#my-div').jPlugin('method1', settings, callback);

谢谢你们!

推荐答案

回答@Felix Kling的意见

Answer in @Felix Kling comments

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

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