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);
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.
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.
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.
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.
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/>`;
}
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With