justinledouxweb justinledouxweb - 3 months ago 11
Javascript Question

Remove jQuery event where this is bound to the handler

I am trying to remove a jQuery event who's callback is bound with

this
. The problem is that
.bind()
creates a new function every time... so when I try removing the event, it is technically not the same function so it doesn't work.

I can't figure out how to keep the right
this
inside the callback in this case:

class Controller {
open() {
$('body').on('click', this.handleClick.bind(this));
}

close() {
$('body').off('click', this.handleClick.bind(this));
}
}

Answer

You can simply use jQuery namespaces:

class Controller {
    open() {
        $('body').on('click.myNamespace', this.handleClick.bind(this));
    }

    close() {
        $('body').off('click.myNamespace');
    }
}