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' );
}
};
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));
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);
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);
Thank you guys!
Answer in @Felix Kling comments