Why jQuery.proxy rocks my world
makuchaku.in
makuchaku.in
https://developer.mozilla.org/en/JavaScript/Reference/Global...
https://developer.mozilla.org/en/JavaScript/Reference/Global...
When we start seeing people using (jQuery.proxy(xxx)()) - then they've learned too much jQuery and not enough Javascript :-)
https://developer.mozilla.org/en/JavaScript/Reference/Global...
Unfortunately, bind is a 5th edition feature, not widely available.
Another nice context-setting trick is to set the context manually when you do ajax requests - then callbacks will have the context of the object you did the request in:
var myobj = {
done: "I'm done.",
load: function(){
$.ajax({
context: this,
success: function(){
alert(this.done);
}
});
}
};It would look something like this
var FBNotificationWatcher = new Class({
Implements: [Options],
options: {
timeout: 500,
url: 'http://dot.com',
onRequestComplete: function(response){}
},
initialize: function(options){
this.setOptions(options);
this.request = new Request({
url: this.options.url,
onComplete: function(resp){
this.processNotifications(resp);
this.options.onRequestComplete(resp);
}.bind(this)
});
this.getNotifications();
},
getNotifications: function(){
this.request.send({//data});
return this;
},
processNotifications: function(rawNotificationData){
//do stuff
this.getNotifications.delay(this.options.timeout, this);
}
});
I'll check out backbone if I'm doing some jQuery dev.Oh how I wish mootools had won the JS library war...
This same problem could easily have been solved by setting a private variable (self, _this, cx, whatever) to this upon instantiation and referring to that instead of this.
In fact, I find myself using that technique (using self-defined variables instead of context) , especially for namespacing.
var myNamespace = {};
(function(cx) {
cx.myClass = function() {
var self = this;
self.action = function() {
self.foo = "bar";
}
};
})(myNamespace);
It makes your code easier to refactor with fewer hard-references to maintain. I'm about to completely give up any usage of "this" for a "var self = this;" upon object-creation.Javascript context-handling is really just too messed up to be dependent on, and while it allows for lots of "cute" hacks, I personally find it creating a lot more problems than it solves.