如何将事件附加到使用backbone.js?
是否可以?像这样的东西:
...
events {
'keydown body' : 'doSmth'
}
...
Is it possible? Something like this:
...
events {
'keydown body' : 'doSmth'
}
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是不可能的,因为 Backbone 使用事件哈希来订阅视图元素(view.el 属性)和元素后代上的事件。它不订阅来自视图元素之外的元素的事件。
因此,如果视图的元素是表格,那么当在表格上触发 keydown 事件时,将调用 doSomething() 函数,但如果在页面上的另一个元素上触发 keydown 事件,则不会调用该函数。
This is not possible because Backbone uses the events hash to subscribe to events on the view's element (view.el property) and the element's descendants. It does not subscribe to events from elements outside the view's element.
So if your view's element is table, then the doSomething() function will be called when the keydown event is fired on the table, but it will not be called if the keydown event is fired on another element on the page.
一般来说,“html”上的 keydown 应该可以工作,请参阅这个问题:
body 上的 keydown?
但是,它是通常最好让 Backbone View 中的事件由 View 的 el 中的元素触发。在这种情况下,您可以使通用应用程序范围的视图接受按键输入:
Generally speaking keydown on 'html' should work, see this question:
keydown on body?
However, it is generally better to have events in a Backbone View be triggered by elements in the View's el. In that case you could make your general app-wide View accept keydown inputs:
只需使用框架(例如 jQuery)在视图的初始化方法中绑定它即可。
不要忘记解绑,这很重要;您可以使用
$(document).find(this.$el).size() 来检查 keyPress 以查看视图是否仍在 dom(文档)中。
Simply bind it using a framework such as jQuery inside the initialize method of the view.
Do not forget to unbind, it's important; you can check in keyPress to see if the view still is in the dom (document) by using
$(document).find(this.$el).size()