I know there is a smart way to utilize closures and do what I am looking for, but I’m not sure what it is.
In the following code:
var MyApp = {
innerObject : {
myData : "test value",
myMethod : function() {
// 'this' ends up referring to HTMLElement, not what I want
alert(this.myData);
}
}
open : function() {
document.getElementById('connectLink').addEventListener('click', this.innerObject.myMethod, false);
}
}
MyApp.open();
I am looking to attach an event handler to the element with id = ‘connectLink’ to a method inside innerObject. That method accesses other data inside innerObject to carry out its function. I know this has something to do with the tricky nature of the keyword this in javascript. Is there a pattern I can adopt to fix this?
Keep a reference to
thisand pass an anonymous function:Also remember that you have to use
attachEventin IE.Update:
Newer browsers provide
.bind()which lets you bind the context of the function to a certain object. This is probably the cleanest solution. The link above provides an implementation for browsers that don’t support it.