admin管理员组文章数量:1419611
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);
本文标签: How do I pass a JavaScript class instance to DOM Event ListenerStack Overflow
版权声明:本文标题:How do I pass a JavaScript class instance to DOM Event Listener? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745317689a2653227.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论