我有一个es6类,它在mousedown上绑定handleElement
,在拖动时它会调整variableElement
的大小。
问题是它不会输出console.log('move')
。虽然如果我重命名_mousemove
函数,我会在两个eventListeners上得到一个未定义的方法错误......
我似乎无法弄清楚发生了什么?
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`;
}
}
答案 0 :(得分:3)
_mousemove
中的this.
未引用this._mousemove
(它指的是DragResizer
) window
无法接听>
旧方式(不使用箭头功能)是设置:
var _this = this;
然后致电
window.addEventListener('mousemove', _this._mousemove);
没有箭头功能:
export default class DragResizer {
constructor(handleElement, variableElement) {
this.handleElement = window.document.getElementsByClassName(handleElement)[0];
this.variableElement = window.document.getElementsByClassName(variableElement)[0];
console.log('bind');
var _this = this;
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`;
}
}
更新我已使用箭头功能重写了上述内容。这是一个working fiddle,下面的代码略有修改,以显示它的工作情况。
export default class DragResizer {
constructor(handleElement, variableElement) {
this.handleElement = window.document.getElementsByClassName(handleElement)[0];
this.variableElement = window.document.getElementsByClassName(variableElement)[0];
console.log('bind');
var _this = this;
this.handleElement.addEventListener('mousedown', () => {
window.addEventListener('mousemove', this._mousemove);
console.log('down');
});
window.addEventListener('mouseup', () => {
console.log('up');
window.removeEventListener('mousemove', this._mousemove);
});
}
_mousemove(event) {
console.log('move');
this.variableElement.style.flexBasis = `${event.clientX}px`;
}
}