I've got an es6 class, that binds a handleElement
on mousedown, and on drag it will resize the variableElement
.
The problem is it won't output the console.log('move')
. Although if I rename the _mousemove
function, I get an undefined method error on the two eventListeners...
I can't seem to figure out what's happening?
export default class DragResizer {
constructor(handleElement, variableElement) {
this.handleElement = window.document.getElementsByClassName(handleElement)[0];
this.variableElement = window.document.getElementsByClassName(variableElement)[0];
console.log('bind');
this.handleElement.addEventListener('mousedown', function () {
window.addEventListener('mousemove', this._mousemove);
console.log('down');
});
window.addEventListener('mouseup', function () {
console.log('up');
window.removeEventListener('mousemove', this._mousemove);
});
}
_mousemove(event) {
console.log('move');
this.variableElement.style.flexBasis = `${event.clientX}px`;
}
}
_mousemove
won't get called since thethis.
inthis._mousemove
does not refer toDragResizer
(it refers towindow
)The old way (without using an arrow function) is to set:
and then call
Without arrow function:
UPDATE I've rewritten the above using arrow functions. Here is a working fiddle with below code slightly modified to show it working.