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:
Expand|Select|Wrap|Line Numbers
- 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:
Expand|Select|Wrap|Line Numbers
- 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???