I am trying to set up a callback in jQuery that correctly binds "this" to the calling object. Specifically, here is the code I am working with. I am doing an ajax call in a Object like this:
Object.prototype.doAjaxCall = function(url)
{
$.get(url, null, this.handleAjaxResponse );
}
However, in Object.prototype.doAjaxCall
, this
does not refer to the correct thing. I have worked with Prototype before and I know you need to bind this when you do the Ajax call, but I can't seem the find the correct way to do that in jQuery. Can someone point me in the right direction?
HTML. The this Keyword is a reference to DOM elements of invocation. We can call all DOM methods on it. $() is a jQuery constructor and in $(this), we are just passing this as a parameter so that we can use the jQuery function and methods.
$(this) is a jQuery wrapper around that element that enables usage of jQuery methods. jQuery calls the callback using apply() to bind this . Calling jQuery a second time (which is a mistake) on the result of $(this) returns an new jQuery object based on the same selector as the first one.
this would refer to the current DOM element h1 which invoked the event. Enclosing it with a $ makes it a jquery object. So $(this) basically refers to the jquery h1 object . So $(this) = $('h1') where h1 is the event which triggered the event.
bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to . bind() occurs.
Use the jQuery ajax context
property to bind this. eg:
$.ajax({
context: this,
url: url,
type: 'GET'
}).done( function(data, textStatus, jqXHR) {
this.handleAjaxResponse();
});
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