removeEventListener for DOM event in helper has no effect

Thanks to Doug who pointed me to the right direction, this works:

startSliderDrag : function(component)
{
    var self = this;
    var mouseMoveHandler = function(event) {
        console.log("move");
        self.anotherFunctionFromHelper(component);
    };

    var mouseUpHandler = function(event) {
        console.log("up");
        document.removeEventListener("mousemove", mouseMoveHandler);
        document.removeEventListener("mouseup", mouseUpHandler);
    };

    document.addEventListener("mousemove", mouseMoveHandler);
    document.addEventListener("mouseup", mouseUpHandler);
},

With that approach I keep the reference to the component and have access to the mouseEvent and can remove the listeners.


This is not a Lightning issue its at the DOM level and would happen in any web tech.

The key here from the doc https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

This means in the addEventListener() call you are specifying a different function than in the removeEventListener() call - these must be exact refs to the same thing.

The .onmousemove= approach would only work if you switch away from addEventListener() for the wire up.


For me the solution was to create a reference to the bound function like this:

this.boundMouseMove = this.mouseMove.bind(this);

and then use this reference for add / remove eventlistener

addEventListener('mousemove', this.boundMouseMove, false);

...

removeEventlistener('mousemove', this.boundMouseMove);

This got rid of the nasty 'self' variable