Reputation: 355
I use CreateJS/EaselJS to create a canvas example. I have a card object (bitmap object), and I add to it an event listener to handle 'mousedown' event. Then I try to remove this event listener, but it seem it is not working. Can anyone help me?
toggleDragDrop: function (stage, state) {
if (state) {
this.graphicsObj.addEventListener("mousedown", function (evt) {
var offset = { x: evt.target.x - evt.stageX, y: evt.target.y - evt.stageY };
// add a handler to the event object's onMouseMove callback
// this will be active until the user releases the mouse button:
evt.addEventListener("mousemove", function (ev) {
ev.target.x = ev.stageX + offset.x;
ev.target.y = ev.stageY + offset.y;
stage.update();
});
});
}
else {
this.graphicsObj.removeEventListener("mousedown");
}
}
Upvotes: 2
Views: 5520
Reputation: 28860
.removeEventListener()
requires two (or three) arguments, not just one. The second argument is a reference to the same listener function that was passed into .addEventListener()
. So you can't use an anonymous function expression with .addEventListener()
if you want to remove it later. Instead, use a named function so you can refer to it in both calls:
toggleDragDrop: function (stage, state) {
function downer( evt ) {
var offset = {
x: evt.target.x - evt.stageX,
y: evt.target.y - evt.stageY
};
// add a handler to the event object's onMouseMove callback
// this will be active until the user releases the mouse button
evt.addEventListener("mousemove", function (ev) {
ev.target.x = ev.stageX + offset.x;
ev.target.y = ev.stageY + offset.y;
stage.update();
});
}
if (state) {
this.graphicsObj.addEventListener("mousedown", downer);
}
else {
this.graphicsObj.removeEventListener("mousedown", downer);
}
}
Upvotes: 2