Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 685
livemac Avatar asked Nov 08 '10 04:11

livemac


People also ask

Is it possible to initiate a DOM event from JavaScript?

HTML DOM events allow JavaScript to register different event handlers on elements in an HTML document. Events are normally used in combination with functions, and the function will not be executed before the event occurs (such as when a user clicks a button).

What method can be used to listen for DOM events?

The addEventListener() method allows you to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object, or other objects that support events, like the xmlHttpRequest object.


1 Answers

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);
like image 190
Zack Bloom Avatar answered Sep 29 '22 15:09

Zack Bloom