无法删除(绑定)事件侦听器

Unable to remove an (bound) event listener

本文关键字:事件 侦听器 绑定 删除      更新时间:2023-09-26

我是javascript的新手,遇到了以下问题,在多次搜索后,我无法在以前的答案中找到(希望这不是重复的)。

我有以下模块/类。假设我正在尝试实现一个可以在屏幕上拖动的组件。当用户第一次点击它时,我们开始监听windowmousemove事件,以了解用户将鼠标移动到的位置。用户释放鼠标后,我们要删除窗口的事件侦听器。代码非常简单,如果我只是在 iife 之外编写代码,它就可以工作。但是,目前removeEventListener根本不起作用。我想这可能与clousure范围或其他东西有关,但我完全错过了它。提前非常感谢您,这是代码:

我的班级.js

 var myNamespace = myNamespace || {};
 (function(myNamespace){
 var onMouseDragDown = function(e){
          window.addEventListener("mousemove", onMouseDragMove,true);
          window.addEventListener("mouseup", onMouseDragUp,false);
       };
  var onMouseDragUp = function(e){
// This code executes, but the events CONTINUE to be triggered after removing the event listener
//The following lines do not seem to have any effect whatsoever even though they are executed when the user releases the mouse button
      window.removeEventListener("mousemove", onMouseDragMove, true);
      window.removeEventListener("mouseup", onMouseDragUp,false);
  };
  var onMouseDragMove = function(e){
      console.log('moving');
   };
   myNamespace.MyClass = function(param){
      this._param = param;
      this._div = document.createElement('div');  
      this._div = ....
      this._div.addEventListener('mousedown', onMouseDragDown.bind(this), false);
   }
   myNameSpace.MyClass.prototype.getDiv = function (){
      return this._div;
   }
)(myNameSpace);

索引.html

        function onCreateNewDocumentClicked(event){
            var myObject = new myNamepace.MyClass(someParams);
            document.body.appendChild(mdi.getDiv());
        }

若要删除事件侦听器,必须提供添加事件侦听器时提供的确切函数。
这里发生的事情是 bind() 每次都会创建一个新函数,所以实际上:

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

若要删除事件侦听器,必须存储添加时提供的函数。

因此,在添加侦听器时存储侦听器,以便以后能够将其删除:

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

我在这里做了一个简短的演示,当您单击第一个按钮时,它会提醒"您好"。
我们看到,通过删除具有新绑定调用的侦听器,它不会删除它。
然后删除存储的函数即可完成这项工作。

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

编辑 :您无需向要拖动的每个div 添加/删除侦听器。相反,您只需在窗口中收听单击,然后使用"目标"事件的信息,这将告知单击了哪个div。
也许你会想停止传播/防止默认处理被点击的div,我不知道。

事件处理程序将如下所示:

 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();
 } 

您可以在窗口或文档对象上一劳永逸地设置它:

document.addEventListener("mousedown", handleMouseDown)

我在这里做了一个小演示,点击一个div看看它已经被识别了:
http://jsbin.com/ilavikI/2/edit

可能是你的

 .bind(this) 

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

不返回对要删除的同一函数的引用?