adding an object method as an event listener

E

Eli

Hello,

****************
function myClass(name) {
this.name=name;
}
myClass.prototype.printName=function(evt) {
try {
if (evt.which==1 || evt.button==1)
document.write('Mr '+this.name);
}
catch (e) {
document.write('Sorry, what is your name?');
}
}
var myObj=myClass('Jhons');
var clickme=document.getElementById('clickme');
clickme.addEvent(clickme,'mousedown',myObj.printName);
****************

When clicking, I get always: "Sorry, what is your name?"..
Consider myObj is not a singleton, and I'm adding the same function to
many elements as event listeners.
How can I get the expected name, when used as event handler?

-thanks, Eli
 
S

scriptguru

Eli напиÑав:
Hello,

****************
function myClass(name) {
this.name=name;
}
myClass.prototype.printName=function(evt) {
try {
if (evt.which==1 || evt.button==1)
document.write('Mr '+this.name);
}
catch (e) {
document.write('Sorry, what is your name?');
}
}
Why try/catch, not just "else"?
var myObj=myClass('Jhons');
var myObj=new myClass('Jhons');
var clickme=document.getElementById('clickme');
clickme.addEvent(clickme,'mousedown',myObj.printName);
Maybe "attachEvent", not an "addEvent"?
Try also
clickme.onmousedown=myObj.printName

Regards,
Val Polyakh
 
E

Eli

Maybe "attachEvent", not an "addEvent"?
addEvent is a wrapper for IE and Mozilla to attach event listeners.

*********
function addEvent(obj,e_type,func) {
if (obj.addEventListener) {
obj.addEventListener(e_type,func,false);
return true;
}
else if (obj.attachEvent) {
var ret=obj.attachEvent('on'+e_type,func);
return ret;
}
return false;
}
function removeEvent(obj,e_type,func) {
if (obj.removeEventListener) {
obj.removeEventListener(e_type,func,false);
return true;
}
else if (obj.detachEvent) {
obj.detachEvent('on'+e_type,func);
return true;
}
return false;
}
*********
Try also
clickme.onmousedown=myObj.printName
In this case, 'this' points to the object itself which is what I want,
but the event object is not transferred to the function.

-thanks, Eli
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,269
Latest member
vinaykumar_nevatia23

Latest Threads

Top