JavaScript Anonymous Function With Parameters From Call()

Go To StackoverFlow.com

2

I am trying to do the following:

function main(callback) {
   $.ajax('server-side', function() {
       this.callback.call("hello");
   }.bind({ callback: callback });
}

main(function(response) {
   alert(response);
});

Response is undefined, I would expect it to be "hello". Any ideas why?

2012-04-04 06:36
by Justin
you wrote "print response" , but print doesnt exist in javascript - mpm 2012-04-04 06:42


4

call first argument should be a reference to "this". Being "this" the context where you want to execute your function. Call function Mozila MDN

2012-04-04 06:43
by mmarinero
Thanks that is the answer - Justin 2012-04-04 06:44
You can omit the .call part and just say this.callback("hello"). And you can omit all of the bind stuff and just use the callback parameter directly as callback("hello") - nnnnnn 2012-04-04 07:08


1

You wrote :

function main(callback) {
   $.ajax('server-side', function() {
       this.callback.call("hello");
   }.bind({ callback: callback });
}

main(function(response) {
   print response;
});

print doesnt exists in javascript.

then you wrote this.callback.call , which is wrong

you should write

callback.call(this,"hello") , 

just check the call function signature.

2012-04-04 06:45
by mpm
Actually need this because of the bind() and bindding an object containing the callback. Need to use bind() because by the time the callback fires from the ajax event the passed in parameter callback will be out of scope - Justin 2012-04-04 06:47
@Justin - the main() function's callback parameter will still be accessible when the ajax callback runs, even though main() will have finished by then, due to the magic of closures. Try it and see.. - nnnnnn 2012-04-04 06:53
Ads