Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Javascript Callback function?

Tags:

javascript

i was wondering how to implement a callback into this piece of code

MyClass.myMethod("sth.", myCallback);
function myCallback() { // do sth };

var MyClass = {

myMethod : function(params, callback) {

    // do some stuff

    FB.method: 'sth.',
       'perms': 'sth.'
       'display': 'iframe'
      },
      function(response) {

            if (response.perms != null) {
                // How to pass response to callback ?
            } else {
                // How to pass response to callback ?
            }
      });
}

}

like image 498
fabian Avatar asked Feb 24 '11 22:02

fabian


1 Answers

three ways to achieve "// How to pass response to callback ?" :

  1. callback(response, otherArg1, otherArg2);
  2. callback.call(this, response, otherArg1, otherArg2);
  3. callback.apply(this, [response, otherArg1, otherArg2]);

1 is the simplest, 2 is in case you want to control the 'this' variable's value inside your callbackfunction, and 3 is similar to 2, but you can pass a variable number of arguments to callback.

here is a decent reference: http://odetocode.com/Blogs/scott/archive/2007/07/05/function-apply-and-function-call-in-javascript.aspx

like image 78
jenming Avatar answered Nov 15 '22 00:11

jenming