Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass multiple arguments into a javascript callback function?

Javascript code:

function doSomething(v1,v2){ //blah; }

function SomeClass(callbackFunction,callbackFuncParameters(*Array*))={
   this.callback = callbackFunction;
   this.method = function(){
       this.callback(parameters[0],parameters[1])  // *.*
   }
}

var obj = new SomeClass( doSomething, Array('v1text','v2text') );

The problem is if I change function doSomething to

function doSomething(v1,v2,v3){ //blah; }

I have to change the corresponding line (marked as //*.*) in SomeClass to

this.callback(parameters[0],parameters[1],parameters[2]);

What can be done to avoid the (*.*) line to be changed no matter how the number of 'doSomething' function's parameters is changed?

Thanks a lot!

like image 349
Shawn Avatar asked Jan 30 '09 07:01

Shawn


People also ask

Can callback functions have parameters?

Yes. The print( ) function takes another function as a parameter and calls it inside. This is valid in JavaScript and we call it a “callback”. So a function that is passed to another function as a parameter is a callback function.

How do you pass a callback function in JavaScript?

Passing a function to another function or passing a function inside another function is known as a Callback Function. Syntax: function geekOne(z) { alert(z); } function geekTwo(a, callback) { callback(a); } prevfn(2, newfn);

Can a function have multiple parameters JavaScript?

Functions can accept more than one argument. When calling a function, you're able to pass multiple arguments to the function; each argument gets stored in a separate parameter and used as a discrete variable within the function.


1 Answers

You probably want to use the apply method

this.callback.apply(this, parameters);

The first parameter to apply indicates the value of "this" within the callback and can be set to any value.

like image 138
krosenvold Avatar answered Sep 16 '22 17:09

krosenvold