I have what seems to be a very tricky situation. I would like to pass an instance of an object to the event listener of a DOM element that was created by that same object instance (if that makes sense).
function Object(callback){
this.callback = callback;
this.node = document.createElement('div');
this.send = function(){
document.getElementById('list').appendChild(this.node);
}
this.node.addEventListener('click',function(){/*this.callback() of Object instance needs to go here*/},true);
}
I know that using callback()
would work inside the event listener, but thats not what I need because I will be using variables from the instance that are not passed from the construct later on.
How can I solve this?
I have what seems to be a very tricky situation. I would like to pass an instance of an object to the event listener of a DOM element that was created by that same object instance (if that makes sense).
function Object(callback){
this.callback = callback;
this.node = document.createElement('div');
this.send = function(){
document.getElementById('list').appendChild(this.node);
}
this.node.addEventListener('click',function(){/*this.callback() of Object instance needs to go here*/},true);
}
I know that using callback()
would work inside the event listener, but thats not what I need because I will be using variables from the instance that are not passed from the construct later on.
How can I solve this?
Share Improve this question edited Jun 29, 2012 at 17:43 machineghost 35.8k32 gold badges173 silver badges262 bronze badges asked Nov 8, 2010 at 4:07 livemaclivemac 1131 silver badge7 bronze badges1 Answer
Reset to default 6The anonymous function changes the meaning of this. To be able to use it within the handler, use another var, or don't create another function:
var elem = this;
this.node.addEventListener('click',function(){ elem.callback(); },true);
or
this.node.addEventListener('click', this.callback, true);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745317689a4622293.html
评论列表(0条)