Reputation: 22732
Is it possible to unbind a listener from within the listener? I want to do this because I have a listener which determines the criteria of its own unbinding (e.g. when a certain key is pressed, the listener should unbind).
$input.on("keydown.listenerOne", function (press) {
if(press=="37"){
$input.off("keyup.listenerOne");
}
});
Upvotes: 1
Views: 279
Reputation:
Yes that's a correct approach. You can unbind it inside the handler but be aware that you have two different events(keyup and keydown). Perhaps you meant keyup.
Upvotes: 3
Reputation: 309
You should be unbinding the same thing you are binding. In this case, you are attempting to unbind keyup
when you hav keydown
bound. Also, press
will not tell you the keyCode, you should do
var code = press.keyCode || press.which;
if(code == 37) { //Enter keycode
//Do something
}
rather than if (press == "37")
taken from this answer
Upvotes: 2
Reputation: 77966
This won't work because you're binding on the keydown
event and unbinding the keyup
event, which has no binding per your example. Also the event you reference as press
would be e
or event
and you'll need to reference the which
property: if(e.which == 37)
Upvotes: 2