我有一个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事件会将"clicked"记录到控制台中,但不会记录为keydown事件.
我四处搜索,似乎,我需要将注意力集中在'视图'上,以便注册'keyDown'事件.所以我将它添加到我的'didInsertElement'函数中:
this.$().focus();
但是,这也不起作用.在旁注中,我将'keyDown'事件添加到扩展Ember.TextArea的Textarea视图中,并且DID注册了keyDown事件.
我在这里错过了什么?
所以我认为出了什么问题,对此的答案在于,除非主元素关注它,否则无法触发'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 }