Search code examples
javascriptcreatejsarrow-functions

createjs off() function to remove listener from js arrow function


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".


Solution

  • 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");