【问题标题】:EmberView 'keydown' and 'keypress' events do not render?EmberView 'keydown' 和 'keypress' 事件不呈现?
【发布时间】:2013-12-17 12:48:30
【问题描述】:

我有一个 EmberApp,它有一个 keyDown 事件,我打算在呈现特定视图时使其可用,我们称之为 PostsCommentView ,为此,我这样做:

App.PostsCommentView = Ember.View.extend({
   eventManager:Ember.Object.extend({
      keyDown:function(event,view){
             console.log("keydown");  // I CAN see this
      },
      click: function(event,view){
              console.log("clicked"); // I CAN see this
      }
   })
    didInsertElement:function(){
              console.log("I have been inserted"); // I CAN see this
    }

});

正如您从我的代码中看到的那样,视图肯定会插入,并且click 事件也会将“点击”记录到控制台中,但不会记录keydown 事件。

我四处搜索,似乎我需要将焦点放在“视图”上才能注册keyDown 事件。所以我将它添加到我的didInsertElement 函数中:

this.$().focus();

但是,这也不起作用。附带说明一下,我将keyDown 事件添加到扩展Ember.TextArea 的Textarea 视图中,并且它确实注册了keyDown 事件。

我在这里错过了什么?

【问题讨论】:

    标签: javascript ember.js dom-events keypress keydown


    【解决方案1】:

    所以我想出了问题所在,这个问题的答案在于除非主要元素有焦点,否则无法触发“keydown”事件。当然,正如我的代码指定的那样,这可以用

    解决
    this.$().focus();
    

    但是,它的深度为 1 级。这个 EmberView 渲染的默认元素是一个 div,它必须是一个 div。除非您明确使用 'tabindex' 属性,将其设置为 -1(不能用标签进入)或 0(可以用标签进入并且是可聚焦的),否则 Div 不能被“聚焦”。

    所以我在视图的 didInsertElement 中这样做了

    didInsertElement(){
       this.$().attr('tabindex',0);
       this.$().focus();
    },
    keyDown:function(){
       console.log('keydown function was triggered') ; // This time it logs itself fine 
    }
    

    【讨论】:

    • 这有点令人难以置信,为什么这不是默认设置?!即使单击视图,它也无法正确聚焦并且无法捕获关键事件!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多