1

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");
   }
});
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
brentonstrine
  • 21,694
  • 25
  • 74
  • 120
  • 2
    Did you try it? Did it work? Also I think `press` would be the event object not which key is pressed. – Musa Nov 05 '12 at 23:54
  • This is not a question, this will work if you change the `off("keyup....` to `off("keydown....`. And you change `press==` to `press.keyCode==` – Andreas Louv Nov 05 '12 at 23:56
  • It wasn't working due to the keydown/keyup inconsistency. I've been staring at my code for too long... – brentonstrine Nov 06 '12 at 00:11

3 Answers3

3

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.

Kirill Ivlev
  • 12,310
  • 5
  • 27
  • 31
2

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)

AlienWebguy
  • 76,997
  • 17
  • 122
  • 145
2

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

Community
  • 1
  • 1
Jeff
  • 309
  • 1
  • 14
  • 1
    Cool, you can simplify even more by removing the ternary and replacing with `var code = press.keyCode || press.which;` – AlienWebguy Nov 05 '12 at 23:59
  • 1
    @AlienWebguy: You can just use `press.which` - jQuery normalises `which` for you so testing for `keyCode` is redundant. – nnnnnn Nov 06 '12 at 00:06
  • Right that's what I used in my answer. I just wanted to mention how Jeff could simplify a ternary. – AlienWebguy Nov 06 '12 at 00:12
  • @nnnnnn I didn't realize jQuery normalized that. I will use it from now on. Thanks. – Jeff Nov 06 '12 at 00:24