I have a little problem in object programming in javascript
There is a "class" Task, it has several methods, a method containing an asynchronous sending of a request with a help of JQuery ($.ajax
). After request is success it's necessary to perform a particular method (e.g. successFunction) of the class Task.
The problem is, after the query in the body of successFunction it's impossible to refer to the class using the keyword this
, because the context has changed, and this contains a reference to the jquery-object which performs an ajax-request.
What variants to refer to the current Task object inside a function that was not caused directly but externally exist? (For example by an event or ajax)
Normally inside an AJAX event such as the success callback, this
refers to the object returned by the $.ajax
call. You could use the context
parameter to change the context in the success callback:
$.ajax({
url: '/foo',
context: this, // <!-- change the context of the success callback
success: function(result) {
// 'this' here will refer to whatever it refered outside
}
});
You could also pass complex objects:
$.ajax({
url: '/foo',
context: { element: this, foo: 'bar' },
success: function(result) {
// you can use 'this.element' and 'this.foo' here
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With