Unable to remove an (bound) event listener

后端 未结 2 406
执念已碎
执念已碎 2021-01-21 16:17

I am a newbie on javascript and I am encountering the following problem, which I wasn\'t able to find in previous answers after searching multiple times (hope this is not a dupl

相关标签:
2条回答
  • 2021-01-21 17:11

    Could it be that your

     .bind(this) 
    

    in

      this._div.addEventListener('mousedown', onMouseDragDown.bind(this), false);
    

    does not return the reference to the same function you are removing?

    0 讨论(0)
  • 2021-01-21 17:18

    To remove an event listener, you must provide the exact function that you provided when adding it.
    What's happening here is that bind() creates a new function each time, so in fact :

    someFunc.bind(someObj) !== someFunc.bind(someObj)
    

    to remove an event listener, you have to store the very function that you provided when adding it.

    so store the listener when you add it to be able to remove it later :

    var someListener = someFunc.bind(someObj);
    element.addEventListener("--", someListener ) ;
    
    // then, later :
    element.removeEventListener('--', someListener);
    

    i made a short demo here, when you click on first button it will alert 'hello'.
    We see that by removing the listener with a new call to bind, it doesn't remove it.
    Then removing the stored function does the job.

    http://jsbin.com/EjevIQA/2/edit

    Edit : you don't need to add / remove a listener to each div you want dragged. instead, you could just listen to click within the window, and make use of the 'target' information of the event, which will tell which div was clicked.
    Maybe you'll want to stop propagation / prevent default when it is a handled div which is clicked, i don't know.

    the event handler will look like :

     function handleMouseDown(e) {
         // you might check here which button was clicked (0=left, 2=right)
         var button = e.button;
         // retrieve the target
         var target = e.target ;
         // check if the target is an object we want to drag
         ...
         ... return otherwise.
         // do some things to initialize the drag.
         ...
         // you might want to prevent the click to bubble / trigger default behaviour :
         e.stopPropagation();
         e.preventDefault();
     } 
    

    you set it up once and for all on the window or document object :

    document.addEventListener("mousedown", handleMouseDown)
    

    I made a tiny demo here, click on a div to see that it has been identified :
    http://jsbin.com/ilavikI/2/edit

    0 讨论(0)
提交回复
热议问题