brentonstrine
brentonstrine

Reputation: 22732

Using .off() while it is nested inside of .on()

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

Answers (3)

user1796666
user1796666

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

Jeff
Jeff

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

SeanCannon
SeanCannon

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

Related Questions