I'm using John Resig's excellent javascript class for simple javascript inheritance and I'm having a spot of bother getting my head around some variable scope problems in relation to the 'this' keyword.
My extended class looks a little like this
var EUNode = Class.extend({
// Methods
//-------------------------------------------------------------------------------
init : function(){
this.div = this.createDiv();
this.canDoStuff = true;
this.div.addEventListener(touchstart, this.touchStartHandler, false);
},
// Create Div
//-------------------------------------------------------------------------------
createDiv : function(){
// code to create a DIV element, add some classes and do some
// other useful stuff
},
touchStartHandler : function(event){
// In here, 'this' refers to the div element, so the
// following condition doesn't work
if(this.canDoStuff){
// do some stuff
}
}
});
I need to be able to reference the EUNode instance from inside the touchStartEventHandler, so I tried the following
var EUNode = Class.extend({
// Methods
//-------------------------------------------------------------------------------
init : function(){
this._super();
// Store a reference to 'this' globally
self = this;
self.div = this.createDiv();
self.canDoStuff = true;
self.div.addEventListener(touchstart, self.touchStartHandler, false);
},
touchStartHandler : function(event){
if(self.canDoStuff){
// Now I can do stuff, but 'self' is now a global variable
// which isn't what I want. If there's more than one instance
// of EUNode, 'self' references the newest instance.
}
}
});
So I'm stuck in a loop. It seems that in order to limit the scope of "self" globally, I need to use the "this" keyword, but "this" means something else inside event handlers. Any tips?