How to pass an instance of a JavaScript class to a DOM Event Listener?

I seem to have a very difficult situation. I would like to pass an instance of the object to the event listener of the DOM element that was created by the same instance of the object (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 use callback()will work inside the event listener, but this is not what I need, because I will use variables from the instance that are not later passed from the construct.

How can i solve this?

+5
source share
1 answer

An anonymous function changes the meaning of this. To be able to use it inside the handler, use another var or do not create another function:

var elem = this;
this.node.addEventListener('click',function(){ elem.callback(); },true);

or

this.node.addEventListener('click', this.callback, true);
+3
source

All Articles