0

I need to write a function:

function doTestConnCall(param1, param2, callbackfun)

param1 & param2 are parameters which I have used inside the function. The 3rd parameter - callbackfun is a function which to be called after finishing doTestConnCall

  1. How to achieve this?
  2. Is it possible to pass 2 callbacks inside a single method. Say doTestConnCall(param1,callback1,callback2)

Think I am missing some basics. Could any one lead me

  • Do you mean to call javascript function from string? Take a look at this http://stackoverflow.com/questions/912596/how-to-turn-a-string-into-a-javascript-function-call – SubRed Nov 25 '12 at 08:10

4 Answers4

1

You can do something like this:

callbackfun(argument1, argument2);

or:

callbackfun.apply(this, [ argument1, argument2 ]);

or:

callbackfun.call(this, argument1, argument2);

The same can be done with multiple callbacks. For example:

callback1.call(this);
callback2.call(this);

See: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/apply

And: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/call

John Kurlak
  • 6,594
  • 7
  • 43
  • 59
0
  1. Call any callback whenever appropriate in the function you are writing--in the case you described, after it completes its core work.

  2. Yes, of course. Call them one after another.

    function multipleCallbacks(arg, arg, callback1, callback2) {
        // Do some stuff
    
        // Do error checking in the real world if you need to be tolerant
        callback1();
        callback2();   
    }
    
Musa
  • 96,336
  • 17
  • 118
  • 137
SAJ14SAJ
  • 1,698
  • 1
  • 13
  • 32
  • 3
    @musa Thanks for the edit, I was trying to fix it but sometimes markdown is evil. Frankly I don't see what you put in is different than what I was doing, but what can you do. – SAJ14SAJ Nov 25 '12 at 07:26
0

Functions in JS are top level constructs. That means function hello() {} is the same as var hello = function() {};. So if you want to pass hello to the function above, you can just call doTestConnCall(param1, param2, hello) after you have defined hello() using either method above.

Sajid
  • 4,381
  • 20
  • 14
0

This is how you achieve it.

It is possible to pass what ever you want to as a method parameter.

function doTestConnCall(param1, param2, callbackfun){
   DO YOUR LOGIC
   callbackfun() // CALL YOUR CALLBACK
}
AMember
  • 3,037
  • 2
  • 33
  • 64