最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to capture the key event from a view? - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question edited Apr 6, 2022 at 18:08 Brian Tompsett - 汤莱恩 5,88372 gold badges61 silver badges133 bronze badges asked May 17, 2011 at 15:13 Running TurtleRunning Turtle 12.8k20 gold badges57 silver badges81 bronze badges 1
  • 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" – Rob Alarcon Commented Jun 30, 2012 at 20:46
Add a comment  | 

2 Answers 2

Reset to default 14

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)

  1. 暂无评论