Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to call a class method with addEventListener?

Tags:

javascript

Just something I've been wondering. In the second parameter in the .addEventListener method, can you call a "(custom) class method" instead of a function?

i.e Would something like the following work?

var object = new ClassName();
document.getElementById('x').addEventListener('click', object.method, false);
like image 769
Azrael Avatar asked Jan 23 '14 03:01

Azrael


People also ask

Can you addEventListener to a class?

To add an event listener to all elements with class: Use the document. querySelectorAll() method to select the elements by class. Use the forEach() method to iterate over the collection of elements.

How do you call a function in addEventListener?

With the addEventListener() method you can specify the propagation type by using the "useCapture" parameter: addEventListener(event, function, useCapture); The default value is false, which will use the bubbling propagation, when the value is set to true, the event uses the capturing propagation.

How do I add an event listener to a specific class?

To add an event listener to all elements with class: Use the document. querySelectorAll() method to select the elements by class. Use the forEach() method to iterate over the collection of elements.

What is the benefit of the addEventListener () method?

The addEventListener() Method – JavaScript Event Listener Example Code. The JavaScript addEventListener() method allows you to set up functions to be called when a specified event happens, such as when a user clicks a button. This tutorial shows you how you can implement addEventListener() in your code.


2 Answers

I just tried a more direct approach, it appears to work and I'd say it's pretty clean. I just add ...bind(this) to the argument to addEventListener(). Don't make it complicated when it's not...

class HTMLExample extends HTMLElement{
  constructor(){
    super();
    this.count = 0;
    this.addEventListener('click', this.onClick.bind(this), false);        
  }
  
  onClick(event){
    let prevCount = this.count;
    this.count++;    
    let msg = `Increased Count from ${prevCount} to ${this.count}`;
    document.getElementById("log").innerHTML += `${msg}<br/>`;     
  }
}
like image 188
OriginalHacker Avatar answered Sep 23 '22 20:09

OriginalHacker


No, what you've written wouldn't work, in that method would be invoked without object as its context. Inside method, this would be set to the DOM element which initiated the event.

If you want to invoke the method and retain the context, close over the object variable with a function:

var object = new ClassName();
document.getElementById('x').addEventListener('click', function () {
  object.method()
}, false);
like image 27
meagar Avatar answered Sep 26 '22 20:09

meagar