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?

1
  • you wrote "print response" , but print doesnt exist in javascript. Commented Apr 4, 2012 at 6:42

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

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").
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.

2 Comments

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 - 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...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.