How do I pass a JavaScript class instance to DOM Event Listener? - Stack Overflow

I have what seems to be a very tricky situation. I would like to pass an instance of an object to the e

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 badges
Add a ment  | 

1 Answer 1

Reset to default 6

The 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信