简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM