开发者

How to capture the key event from a view?

开发者 https://www.devze.com 2023-03-06 07:20 出处:网络
I\'m trying to capture the key event from a view as follows: myView = Backbone.View.extend({ el: $(\'#someDiv\'),

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

myView = Backbone.View.extend({

  el: $('#someDiv'),
  initialize: function(){
    // initialize some subviews
开发者_如何学JAVA  },
  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.


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

_.bindAll(this, 'on_keypress');
$(document).bind('keypress', this.on_keypress);


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号