1

I wants to remove event listener that are already in event listener.My Code is

  public componentDidMount() {
this.drags();
}
private drags(){
 const e = ReactDOM.findDOMNode(this.container);
    if (e) {
      e.addEventListener("mousedown", (event: any) => {
      ....
       parent = ReactDOM.findDOMNode(this).parentNode;
       if (parent) {
         parent.addEventListener("mousemove", (event1: any) => {
         ....
         const eDrag = parent.getElementsByClassName("draggable");
          eRes[0].addEventListener("mouseup", (event3: any) => {
          **// HERE I WANT TO REMOVE LISTENER OF PARENT OF MOUSE MOVE**
          }
        }
       }

    }
  }

}

Can anybody help me in this ?

Nope
  • 22,147
  • 7
  • 47
  • 72
Neha Takhi
  • 41
  • 4
  • Use [**removeEventListener**](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener) - You need to match the listener, best done with "named" listeners, as explained in the linked Documentation above, i.e: `parent.addEventListener("mousemove", yourNamedHandler)` then do `parent.removeEventListener("mousemove", yourNamedHandler)` - This is basic JavaScript and you should find lots of examples on SO, Google and the linked MDN Documentation. – Nope Apr 18 '18 at 11:32
  • If you just want to brute force remove any/all event listeners instead of removing them individually from an element you are quicker cloning the element and replacing it as that removes all listeners as seen here: https://stackoverflow.com/questions/9251837/how-to-remove-all-listeners-in-an-element – Nope Apr 18 '18 at 11:38

1 Answers1

1

Do not use anonymous function as the event handler, use a named function instead.

So, if you add the listener this way:

function doSomething() {
  // something 
}

window.addEventListener('mousedown', this.doSomething);

You can remove it like:

window.removeEventListener('mousedown', this.doSomething);
Jackyef
  • 4,734
  • 18
  • 26
  • As Per code , mouseup event is adding in mousemove event which is parent. Now from child , i wants to remove parent mousemove listener. – Neha Takhi Apr 18 '18 at 11:20
  • Of course, the point is using named function. Have you tried to do parent.removeEventListener, but actually using named function? – Jackyef Apr 18 '18 at 11:31