11

I'm trying to capture the key event from a view as follows:

myView = Backbone.View.extend({

  el: $('#someDiv'),
  initialize: function(){
    // initialize some subviews
  },
  render: function(){
    return this;
  },
  events:{
   'keypress #someDiv': 'showKey'
  },
  showKey: function(e){
    console.log(e.keyCode);
  }
})

That does not work ?

ps: There a no [input] elements in the view or its subviews. I just need to know if the user presses any key and then do something on the view.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Running Turtle
  • 12,360
  • 20
  • 55
  • 73
  • I used your code and work, the only thing you need to remember is that the element you want to add an event must be within "View el" for example the element you want to attach an event must be within "#someDiv" – Roberto Alarcon Jun 30 '12 at 20:46

2 Answers2

14

You can do this in the view initialize() function:

_.bindAll(this, 'on_keypress');
$(document).bind('keypress', this.on_keypress);
Dan Caragea
  • 1,784
  • 1
  • 19
  • 24
  • just found out today: if you have problems with the keypresses not working in chrome use the 'keydown' event instead of keypress. – Dan Caragea Jul 15 '11 at 14:13
  • 14
    Be careful with binding a keypress to the document, it won't unbind with the rest of the events when you remove your view. When you remove your view, also call: $(document).unbind('keypress', 'on_keypress'); – MrGrigg Oct 20 '11 at 01:26
  • When I removed my view, I had to do `$(document).unbind('keypress', this.on_keypress)`. Almost like MrGrigg's answer, but passing the actual function, not a string of its name. – Sarah Vessels Jul 18 '14 at 14:10
4

Key pressed goes to the focused element on the page. If you have nothing in your view and the view does not have any focus, then you will not have any key press events.

( btw if you want to do key press event for this.el, do "keypress" : "showKey" )

In you above code the body will most likely receive all keypress events.

Julien
  • 9,216
  • 4
  • 37
  • 38