Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - pass parameters when using .call()

How can you pass parameters to a function when using .call() in Javascript?

When I pass parameters they are always undefined in the callback function

EDIT (an example):

I will have an options object in my plugin:

var options = {

errorCallback : function( errors ) {}

}

I will call this from my plugin like this:

var errors = "Test error list";
configs.errorCallback.call(errors);

I will initialise my plugin like this

 $('#plugin-element').myPlugin(
       { 
           'errorCallback' : function errorrCallbackFunction( errors ) {
                   console.log(errors) //always undefined
               }
       }
like image 310
Drew Avatar asked May 16 '11 10:05

Drew


2 Answers

The first argument of call is the 'this' of the function. If you want to pass the variable as argument start from the second one.

configs.errorCallback.call(undefined, errors);

Here is the documentation: Function.prototype.call()

like image 168
mck89 Avatar answered Nov 12 '22 13:11

mck89


configs.errorCallback.call(errors);

This isn't necessary. You only need to use call if you want to set the context of the function call. That means the value of this within the callback.

If you don't want to set this, then you can just call the function as you normally would:

configs.errorCallback(errors);

If you do want to set this, then you need to set it as the first parameter to call. Subsequent parameters are passed on to the function.

For example:

var configs = {
    errorCallback : function( errors ) {}
};
configs.errorCallback.call(configs, errors);

Within errorCallback, you can access configs using the keyword this.

like image 28
lonesomeday Avatar answered Nov 12 '22 12:11

lonesomeday