views:

20818

answers:

4

I understand passing in a function to another function as a callback and having it execute, but I'm not understanding the best implementation to do that. I'm looking for a very basic example, like this:

var myCallBackExample = {
    myFirstFunction : function( param1, param2, callback ) {
     // Do something with param1 and param2.
     if ( arguments.length == 3 ) {
      // Execute callback function.
      // What is the "best" way to do this?
     }
    },
    mySecondFunction : function() {
     myFirstFunction( false, true, function() {
      // When this anonymous function is called, execute it.
     });
    }
};

In myFirstFunction, if I do return new callback(), then it works and executes the anonymous function, but that doesn't seem like the correct approach to me.

+1  A: 

Callbacks are about signals and "new" is about creating object instances.

In this case it would be even more appropriate to execute just "callback();" than "return new callback()" because you aren't doing anything with a return value anyway.

(And the arguments.length==3 test is really clunky, fwiw, better to check that callback param exists and is a function.)

annakata
+15  A: 

You can just say

callback();

Alternately you can use the "call" method if you want to adjust the value of "this" within the callback.

callback.call( newValueForThis);

Isnide the function "this" would be whatever "newValueForThis" is.

krosenvold
+4  A: 

There are 3 main possibilities to execute a function:

var callback = function(x, y) {
    // "this" may be different depending how you call the function
    alert(this);
};
  1. callback(argument_1, argument_2);
  2. callback.call(some_object, argument_1, argument_2);
  3. callback.apply(some_object, [argument_1, argument_2]);

The method you choose depends whether:

  1. You have the arguments stored in an Array or as distinct variables.
  2. You want to call that function in the context of some object. In this case, using the "this" keyword in that callback would reference the object passed as argument in call() or apply(). If you don't want to pass the object context, use null or undefined. In the latter case the global object would be used for "this".

Docs for Function.call, Function.apply

Ionuț G. Stan
A: 

this is a goood answer for ajax callbacks.

absra
but this is not
JustinStolle