How to bind "this" for jQuery callbacks?

I am trying to set up a callback in jQuery that correctly binds "this" to the caller. In particular, here is the code I'm working with. I am making an ajax call in an object like this:

Object.prototype.doAjaxCall = function(url) { $.get(url, null, this.handleAjaxResponse ); } 

However, in Object.prototype.doAjaxCall , this does not refer to the right thing. I previously worked with Prototype, and I know you need to bind this when you make an Ajax call, but I cannot find the right way to do this in jQuery. Can someone point me in the right direction?

+6
jquery ajax
source share
2 answers

A more robust, built-in binding function should be part of ECMAScript 3.1. Meanwhile...

 Object.prototype.doAjaxCall = function(url) { var bind = function(context, method) { return function() { return method.apply(context, arguments); }; }; $.get(url, null, bind(this, this.handleAjaxResponse)); }; 
+1
source share

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

 $.ajax({ context: this, url: url, type: 'GET' }).done( function(data, textStatus, jqXHR) { this.handleAjaxResponse(); }); 
+2
source share

All Articles