I'm going through the JavaScript30 challenge, and in lesson 3 he's got some event listener calling a function that references the element it's called on as this
:
const inputs = document.querySelectorAll('.controls input');
function handleUpdate() {
const suffix = this.dataset.sizing || '';
document.documentElement.style.setProperty(`--${this.name}`, this.value + suffix);
}
inputs.forEach(input => input.addEventListener('change', handleUpdate));
inputs.forEach(input => input.addEventListener('mousemove', handleUpdate));
I'm trying to rewrite it with ES6 arrow function, but I can't get the this
to work right. I got a workaround using target
:
const handleUpdate = (e) => {
const that = e.target;
const newValue = `${that.value}${that.dataset.sizing || ''}`;
etc.
}
but I first tried to bind the function like that:
input.addEventListener('change', handleUpdate.bind(this));
But this
inside the function still points to window
and I don't understand why.
Is there no "right" way to bind the function to the element in this case?