Hi.
I want to add an event handler inside a function that will be used has an object constructor. The event handler to be added is an "method" of the object.
if i do this:
This gives an exception. The problem is then the event listener is called the "this" reference is no longer the object but it is the html element that generated the event.
if i declare a local var to store the this reference so the function in the event handler can find the correct object, something like this:
this will not work either because the "me" reference is always set to the last object that was created an not the object that registered the event.
How do i solve this?
Any ideas???
I want to add an event handler inside a function that will be used has an object constructor. The event handler to be added is an "method" of the object.
if i do this:
Code:
function Someobj(element) {
this.num = 1;
this.inc = function() {
++this.num;
}
this.element = element;
element.addEventListener('click', function(event) { this.inc(); }, false);
}
var so1 = new Someobj(document.getElementById('Photo1'));
var so2 = new Someobj(document.getElementById('Photo2'));
if i declare a local var to store the this reference so the function in the event handler can find the correct object, something like this:
Code:
function Someobj(element) {
var me = this;
this.num = 1;
this.inc = function() {
++this.num;
}
this.element = element;
element.addEventListener('click', function(event) { me.inc(); }, false);
}
var so1 = new Someobj(document.getElementById('Photo1'));
var so2 = new Someobj(document.getElementById('Photo2'));
How do i solve this?
Any ideas???
Comment