我是 javascript 的新手,遇到以下问题,在多次搜索后我无法在以前的答案中找到(希望这不是重复的)。
我有以下模块/类。假设我正在尝试实现一个可以在屏幕上拖动的组件。当用户第一次点击它时,我们开始监听 的mousemove
事件window
以了解用户将鼠标移动到哪里。一旦用户释放鼠标,我们想要移除窗口的事件监听器。该代码非常简单,如果我只是在 iife 之外对其进行编码,它就可以工作。但是,目前removeEventListener
根本行不通。我想这可能与clousure,范围或其他东西有关,但我完全错过了它。非常感谢您,这里是代码:
MyClass.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());
}