As a newcomer to javascript, I'm facing an issue that I couldn't find answers to despite searching extensively. Here is my problem: I have a module or class where I am attempting to create a draggable component on the screen. The objective is to listen for mousemove events when the user first clicks on it and then remove these event listeners once the user releases the mouse.
The code appears simple and straightforward, and it works fine when not inside an IIFE (Immediately-Invoked Function Expression). However, the removeEventListener
doesn't seem to work as expected. I suspect it has something to do with closures, scope, or some other concept that I am missing. Your help will be greatly appreciated. Below is the code:
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);
Index.html
...
function onCreateNewDocumentClicked(event){
var myObject = new myNamepace.MyClass(someParams);
document.body.appendChild(mdi.getDiv());
}