By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,384 Members | 1,886 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,384 IT Pros & Developers. It's quick & easy.

adding an object method as an event listener

P: n/a
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.printNa me);
****************

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

Sep 5 '06 #1
Share this Question
Share on Google+
3 Replies


P: n/a

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.printNa me);
Maybe "attachEvent", not an "addEvent"?
Try also
clickme.onmousedown=myObj.printName

Regards,
Val Polyakh

Sep 5 '06 #2

P: n/a
Eli

sc********@gmail.com wrote:
var clickme=document.getElementById('clickme');
clickme.addEvent(clickme,'mousedown',myObj.printNa me);
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

Sep 5 '06 #3

P: n/a
Eli
OK.. already solved it.. :-)

-thanks, Eli

Sep 6 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.