Why jQuery.proxy rocks my world!
Its been very recent that I’m seriously looking into Javascript – and trust me, there is no dearth of stuff that can be achieved with purely client side code (HTML/CSS/JS). With the modern browsers churning out best of the breed in JS environments (both headed & headless), everything is going to come to a browser near you! Its just a matter of time!
Anyways, on more subtle issues, while writing a purely client side JS app using Backbone.js & jQuery Mobile I came across jQuery.proxy method – something that I’ve really started using almost everywhere.. The method is so useful that sometimes I wonder – why jQuery did not implement it in callback mechanism by default.
A quick overview about the problem…
-
var FBNotificationWatcher = new JS.Class({
-
-
initialize : function(timeout) {
-
this.url = "http://foo/return/json";
-
this.getNotifications(); // initiate the first fetch
-
},
-
-
getNotifications : function() {
-
$.ajax({
-
// do your ajax call
-
url : this.url;
-
success : this.processNotifications
-
});
-
},
-
-
processNotifications : function(rawNotificationData) {
-
// process notifications… AND
-
setTimeout(jQuery.proxy(this.getNotifications, this), this.timeout); // start all over again…
-
});
When a new object of FBNotificationWatcher is created, all goes well. this.getNotifications gets the JSON & this.processNotifications processes it. However, when setTimeout’s occurs and this.getNotifications is called again, the context of “this” is set to the “window” object. And because of this, the code breaks in this.getNotifications method.
Now this is very frustrating – as you just lost the object you were operating within.
Solution? jQuery.proxy comes to rescue!
-
processNotifications : function(rawNotificationData) {
-
// process notifications…
-
-
setTimeout(jQuery.proxy(this.getNotifications, this), this.timeout); // start all over again…
-
}
If we setup the setTimeout call like this, jQuery will guarantee that the context of “this” when this.getNotifications gets executed, will always be set to the original FBNotificationWatcher object which had setup the timer. The second argument to jQuery.proxy defines the context you want to get back when the setTimeout callback gets executed.
This concept can be used anywhere you want your callbacks to retain their context.
Read more about the method at jQuery API docs.
Related posts:
- Kickass MCV for your Javascript Apps Very recently, I had an opportunity to work on a...
- How to commission developer machines in an agile way? During the past year – working at AdoMado, I’ve seen myself...
Related posts brought to you by Yet Another Related Posts Plugin.








