2

I am using backbone.js with underscore.js for my web application. I need to detect the escape key event hit for a view.

I know the jquery way of doing this is by checking the event code something like (e.keyCode == 27) on keyup, I wanted to know how to write this in events of my backbone view.

Please advice.

Yasser Shaikh
  • 46,934
  • 46
  • 204
  • 281
  • 3
    `I know the jquery way...` That has nothing to do with jQuery, you can do that perfectly fine with native JavaScript events. This is the problem with people learning how to use a library before learning how things like the API work themselves. On the upside - jQuery _does_ normalize keyboard events across old browsers. – Benjamin Gruenbaum Aug 31 '13 at 17:11

2 Answers2

7

In your Backbone.View:

events : {
  'keydown' : 'keydownHandler'
},

keydownHandler : function (e) {
  switch (e.which) {
    // esc
    case 27 :
      // do things...
      break;
  }
}
Vitalii Petrychuk
  • 14,035
  • 8
  • 51
  • 55
  • 1
    AWESOME ! this works just fine... but i have to get control on my textbox and then hit escape key for this to work... Wot change should i do so that I dont have to click on my textbox and still the escape key event is triggered ? – Yasser Shaikh Aug 31 '13 at 17:15
  • In this case you have to add keydown event to the body for example. You can do it in two ways - create a view with `el: 'body'` or add event in a jQuery way – Vitalii Petrychuk Aug 31 '13 at 17:18
  • You have to look for: e.keyCode [http://stackoverflow.com/questions/6033010/how-to-capture-the-key-event-from-a-view] – Cabuxa.Mapache Feb 18 '14 at 11:21
  • No way. He have to look for `e.which` – Vitalii Petrychuk Feb 18 '14 at 13:22
0

event.keyCode has nothing to do with jQuery. You can use event.keyCode in Backbone just the same. I have never worked with backbone, but I think you do something like this to attach the event.

events: {
    'submit': 'submit'
},

submit: function( event ) {
   if( event.keyCode === 27 ) {
       // Code....
   }
}
iConnor
  • 19,997
  • 14
  • 62
  • 97