回调函数到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