1

I use the on() function of createjs:

myObj.on("mousedown", (e)=>{
    this.myObjMouseDown(e);
});

now, I want to remove the listener, I trying to write this code, with the off() function:

myObj.off("mousedown", (e)=>{
    this.myObjMouseDown(e);
});

but, The code does not seem to be working correctly.

How should I write to cancel the event?

Note: Notice that I need to use an arrow function, because of the word "this".

Rachel
  • 25
  • 4
  • Does createjs provide the `on`/`off` event handler methods? Or are you also loading in jQuery? – Seth Nov 21 '19 at 13:16
  • no jQuery. only createjs and zimjs. the on() is method of createjs. – Rachel Nov 21 '19 at 21:07
  • You can also just use the 3rd parameter (scope) if you don't want to use an arrow function. `obj.on("click", fn, this);` – Lanny Nov 21 '19 at 22:42
  • https://stackoverflow.com/questions/56594241/how-to-be-able-to-remove-event-listener-while-maintaining-access-to-this – Bergi Nov 22 '19 at 01:24

1 Answers1

2

You have to pass a reference to the same function -- but it is important to note that the on method creates a wrapper function for you no matter what, since it also allows you to do pass a scope parameter. The on/off methods were made specifically to address the issue of scope in ES5. (docs)

The best way to make sure you can unsubscribe is to store a reference to the value of the on function call, and pass that to off().

var evt = obj.on("click", () => doSomething());
// later
obj.off("click", evt);

Another great way to cancel events is to remove them in the function callback:

doSomething(evt) {
    // Your Code
    if (condition) {
        evt.remove();
    }
}

Lastly, if you are just looking for a clean-up, use removeAllEventListeners (docs), which you can pass an optional event type to.

obj.removeAllEventListeners("click");
Lanny
  • 11,244
  • 1
  • 22
  • 30