Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind "this" for jQuery callbacks?

Tags:

jquery

ajax

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?

like image 426
Sam Lee Avatar asked Aug 07 '09 06:08

Sam Lee


People also ask

Can you use this in jQuery?

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.

What does $( this mean in jQuery?

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

When we should use $( this in jQuery?

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.

What is the purpose of using bind () method in jQuery?

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.


1 Answers

Use the jQuery ajax context property to bind this. eg:

$.ajax({
    context: this,
    url: url,
    type: 'GET'
}).done( function(data, textStatus, jqXHR) {
    this.handleAjaxResponse();
});
like image 182
David Douglas Avatar answered Sep 19 '22 21:09

David Douglas