In my web application I have a custom object which I've defined with an object function constructor and applied various shared properties through the constructors prototype.
MyObject = function (Name) {
this.Name = Name;
this.ListItem1 = document.createElement('li');
this.ListItem1.onclick = this.SetActive;
this.ListItem2 = document.createElement('li');
this.ListItem2.onclick = this.SetActive;
}
MyObject.prototype.SetActive = function () {
alert('SetActive: ' + this.Name);
}
Now this is a simplified example, my actual object has many more DOM elements attached to it, and each of those DOM elements have many different event listeners. My object also has many other properties and methods as well. I could also potentially have thousands of instances of this object, so code efficiency is important.
My issue right now is that when a DOM event is triggered, the event handler's 'this' property is set to the actual DOM element, not my object instance.
For example:
var HelloObj = new MyObject('Hello');
HelloObj.SetActive();
//This alerts 'SetActive: Hello'
HelloObj.ListItem1.click();
//This alerts 'SetActive: undefined' because 'this' in SetActive
//becomes ListItem1 and obviously ListItem1.Name is undefined
So how can I set the DOM element's event handlers to a function pointer (not a new function instance for each event handler which would be inefficient when there's a large number of object instances) but still retain the context of the object instance itself in regards to 'this'?