开发者

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

开发者 https://www.devze.com 2023-01-23 18:46 出处:网络
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

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?


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消