jQuery插件的回调函数
我怀疑Javascript中的“调用”function。 我有这个jQuery插件:
(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插件文档中的这一行感到有点困惑:
return methods[method].apply( this, Array.prototype.slice.call(arguments, 1));
该插件按预期工作,没有传递回调。 但是如果我像这样调用插件,我该如何将回调传递给正确的方法呢?
$('#my-div').jPlugin('method1', settings);
回调函数应该是设置对象的一部分还是我可以调整插件来接受它?
$('#my-div').jPlugin('method1', settings, callback);
感谢你们!
回答@Felix Kling的评论