It appears the listeners are not removed here. Any idea how to fix this? I am guessing it is to do with the manner I "share" the listener and I'm using arrow functions (per recommendation here https://medium.freecodecamp.org/reactjs-pass-parameters-to-event-handlers-ca1f5c422b9)
Code:
import * as React from 'react';
export default class ITestComponent extends React.Component {
public render() {
return (
<div>
<div
onMouseDown={this.handleMouseDown('horizontal')}
draggable={false}
style={{ border: '1px solid blue', padding:20 }}
>
Horizontal Drag Test
</div>
<div
onMouseDown={this.handleMouseDown('vertical')}
draggable={false}
style={{ border: '1px solid green', padding:20 }}
>
Vertical Drag Test
</div>
</div>
);
}
private handleMouseDown = (eType:string) => (e:any) => {
console.log('Add Event Listeners (handleMouseDown)', eType)
window.addEventListener('mousemove', this.handleMouseMove(eType))
window.addEventListener('mouseup', this.handleMouseUp(eType))
}
private handleMouseMove = (eType:string) => (e:MouseEvent) => {
console.log(' - handleMouseMove', eType, e.clientY)
};
private handleMouseUp = (eType:string) => (e:MouseEvent) => {
console.log('Remove Listeners (handleMouseUp)', eType)
window.removeEventListener('mousemove', this.handleMouseMove(eType))
window.removeEventListener('mouseup', this.handleMouseUp(eType));
};
}
Console Output after clicking on "horzontal drag test" and dragging down (with mouse button depressed), the releasing mouse button, then dragging a little more..
Add Event Listeners (handleMouseDown) horizontal
- handleMouseMove horizontal 61
...
- handleMouseMove horizontal 220
- handleMouseMove horizontal 221
Remove Listeners (handleMouseUp) horizontal
- handleMouseMove horizontal 222
- handleMouseMove horizontal 222
- handleMouseMove horizontal 228
...
Question specifically is how to retain the concept of "reusing" the event handler for multiple purposes?
Note I'm not using an anonymous function here like in one of the suggested answers (Javascript removeEventListener not working)