Max Koretskyi
Max Koretskyi

Reputation: 105507

can't unbind custom handler from document.keydown event

I'm binding my custom handler to keydown event of the `document:

this._bindCloseDlgEvents = function() {
    $(document).keydown(closeDlgByEscClick.bind(this));
};

I've checked and the event is bound: $._data( document, "events" ) returns {keydown: Array[1]}. Now I'm trying to unbind the same handler:

this._unbindCloseDlgEvents = function() {
    $(document).off('keydown', closeDlgByEscClick);
};

Checking with $._data( document, "events" ) - nothing is changed {keydown: Array[1]}. Why so? If I unbind in this way $(document).off('keydown') the event is unbound, but I need to unbind only my specific handler.

Upvotes: 0

Views: 146

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

since you are using .bind() it returns a new anonymous function.

Use namespaced event handler like

this._bindCloseDlgEvents = function() {
    $(document).on('keydown.closedialogevent', closeDlgByEscClick.bind(this));
};

then

this._unbindCloseDlgEvents = function() {
    $(document).off('keydown.closedialogevent');
};

.bind()

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Demo: Fiddle

Upvotes: 1

Related Questions