Javascript Backbone.js - 在视图处于活动状态时添加 keydown 事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7105393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Backbone.js - Adding keydown events when view is active?
提问by Pauly Dee
I have a view called gallery that options. I want to listen and act on keydown events when the gallery is rendered (until it's closed).
我有一个名为画廊的视图选项。我想在渲染图库时监听并处理 keydown 事件(直到它关闭)。
How do I do this in backbone events? I've tried all variations of 'keydown X':function and none have worked.
我如何在骨干事件中做到这一点?我已经尝试了 'keydown X':function 的所有变体,但都没有奏效。
回答by fearphage
I just tested the following and it worked flawlessly:
我刚刚测试了以下内容,它完美无缺:
var view = Backbone.View.extend({
// ... snip ...
events: {
'keyup :input': 'logKey'
,'keypress :input': 'logKey'
}
,logKey: function(e) {
console.log(e.type, e.keyCode);
}
});
I'd go back and check your code. All events in Backbone are defined as delegates attached to the viewInstance.el
element. To unbind the events, call viewInstance.remove()
which calls $(viewInstance.el).remove()
under the covers and cleans up all the delegated events.
我会回去检查你的代码。Backbone 中的所有事件都定义为附加到viewInstance.el
元素的委托。要取消绑定事件,请调用viewInstance.remove()
which 调用$(viewInstance.el).remove()
并清除所有委托的事件。
Also note that in some browsers (Firefox I believe) there's a known issue that some keys (like arrow keys) don't bubble and will not work properly with delegated keypress
events. If you're catching special keys, you're probably better off using keyup
and keydown
.
另请注意,在某些浏览器(我相信是 Firefox)中,存在一个已知问题,即某些键(如箭头键)不会冒泡,并且无法与委托keypress
事件一起正常工作。如果您要捕获特殊键,则最好使用keyup
和keydown
。