Reputation: 5463
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 ?
}
});
}
}
Upvotes: 5
Views: 11572
Reputation: 4935
I think you can simply call callback(response.perms)
there. You could also register it as a
member of your class:
MyClass.cb = callback;
and later call it:
MyClass.cb(response.perms)
Upvotes: 1
Reputation: 809
three ways to achieve "// How to pass response to callback ?" :
callback(response, otherArg1, otherArg2);
callback.call(this, response, otherArg1, otherArg2);
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
Upvotes: 13
Reputation: 5463
MyClass.myMethod("sth.", myCallback);
var 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) {
callback();
} else {
callback();
}
});
}
}
Upvotes: 0
Reputation: 50592
You're close... just use the callback. In this instance, you can form a closure.
var MyClass = {
myMethod : function(params, callback) {
// do some stuff
FB.method: 'sth.',
'perms': 'sth.'
'display': 'iframe'
},
function(response) {
if (response.perms != null) {
callback(response);
} else {
// response is null, but you can pass it the same as you did above - if you want to. Probably better to have a generic failure handler
ajaxFailHandler();
}
});
}
Upvotes: 1
Reputation: 6307
All you have to do is call the callback function the normal way. In this case you would just do callback(response)
.
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 ?
// Easy as:
callback(response);
} else {
// How to pass response to callback ?
// Again:
callback(response);
}
});
}
}
Upvotes: 7
Reputation: 44632
You've got a reference to a function now. Just invoke it:
callback(response.perms);
Upvotes: -1