3

I'm having trouble figuring out how to correctly reference the 'right' 'this' in a jquery ajax callback.

I have a javascript class where I define the callback:

Foo.prototype.onCallback = function(response) {
  // 'this' should refer to an instance of foo in both the following cases
  this.bar(...)    
  this.hello(...)
}

outside of the class I have:

foo1 = new Foo()
myCallback = foo1.onCallback;

$.ajax({
  ...
  success: function(response) {myCallback(response); ... }
});

Right now I believe 'this' within foo1.onCallback is referring to the html element the ajax call is attached to. How do I ensure that 'this' refers to foo1? Is there a better way to do this?

4 Answers 4

4

You could use the context property of $.ajax:

var foo1 = new Foo();

$.ajax({
  context: foo1,
  success: function(response) { this.onCallback(response); }
});

...which causes this in the callback to reference your Foo object.

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

2 Comments

Thanks for the edit @Rocket. I totally missed that I grabbed the wrong identifier. :)
No prob, figured it was just a typo, so I fixed it for ya :-P
2

You can't do that.

You must either write:

$.ajax({
  ...
  success: function(response) { foo1.onCallback(response); ... }
});

or this:

myCallback = foo1.onCallback.bind(foo1);

Note that Function.bind() requires ECMAScript 5.

Comments

1

Use the following idiom:

myCallback = foo1.onCallback.bind(foo1);

In fact you should take advantage of first-class function support in JavaScript even further:

foo1 = new Foo()

$.ajax({
  ...
  success: foo1.myCallback.bind(foo1)
});

See also:

1 Comment

the OP indicated that there were other things to be done after the initial callback was called, so you can't just pass it as the success: parameter.
-1

You could simply add the statement alert(this); to see the if it is foo1.

1 Comment

Your alert would output [object Object]

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.