I'm quite new on JS and got stuck on this problem. So I have this constructor which I understand how its works EXCEPT for one thing. How does an event handler got called from inside of an object or function?
I thought event handler could only be placed on global scope directly, not inside a function/object or another block scopes.
class Counter {
constructor(element, defaultValue) {
this.element = element;
this.value = defaultValue;
this.valueDOM = element.querySelector('.value');
this.valueDOM.textContent = this.value;
this.increase = this.increase.bind(this);
this.btnIncrease = element.querySelector('.increase');
this.btnIncrease.addEventListener('click', this.increase);
}
increase() {
this.value++;
this.valueDOM.textContent = this.value;
}
}
const counterOne = new Counter(document.querySelector('.counter-one'), 0);
const counterTwo = new Counter(document.querySelector('.counter-two'), 0);
The HTML is quite simple, just a plain old counter like this.
<div class="container counter-one">
<span class="value">0</span>
<button class="increase">+</button>
</div>
<div class="container counter-two">
<span class="value">0</span>
<button class="increase">+</button>
</div>
addEventListener in this case is pointing directly at the local object's this.increase method. It is not pointing at the object's prototype function, but an actual distinct copy of that function which is attached to the object instance. Does that help?