在backbone.js中如何将keyup绑定到文档
我一直在关注backbone.js 的 Railscast 教程,我想扩展该功能以包括键盘控制。我将以下内容添加到我的节目视图中:
class Raffler.Views.EntryShow extends Backbone.View
template: JST['entries/show']
events:
'click .back': 'showListing'
'keyup': 'goBack'
showListing: ->
Backbone.history.navigate("/", trigger: true)
goBack: (e) ->
console.log e.type, e.keyCode
render: ->
$(@el).html(@template(entry: @model))
this
在我的节目模板上,我有以下内容:
<a href="#" class="back">Back</a>
<%= @entry.get('name') %></td>
如果我使用 Tab 键选择后退链接,然后开始按随机键,我会在 javascript 控制台中获得输出。但是,如果我加载页面并且不选择链接并开始敲击按键,我的控制台中将不会有任何输出。
如何将事件绑定到文档,以便在加载屏幕时监听按下的任何按键?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将需要解决主干视图的范围。
当您执行以下操作时:
您将
goBack
函数绑定到视图的容器元素上引发的 keyup 事件。 (默认情况下,渲染视图的 div)而不是这样做,如果您想绑定到视图之外的某些内容(没有自己的视图!(*))
(*)备注 如上所述,只有当您要绑定的项目没有自己的视图时,如果您有完整页面的视图(应用程序视图或类似的视图),您最好才执行此操作)你可以在那里绑定 keyup,然后提出一个例如,事件
App.trigger('keypressed', e);
。然后,您可以在 EntryShow 视图中绑定到该应用程序的
keypressed
事件。请记住,在某些情况下,您应该将某些操作作为延迟事件或将按键分组在一起,因为触发体内发生的每个按键可能会对性能造成很大影响。尤其是在较旧的浏览器上。
You will need to work around backbone's scope for views.
when you are doing something like this:
you are binding your
goBack
function to the keyup event raised on your container element of your view. (by default the div in which the view is rendered)instead of doing that, if you want to bind to something outside your view (which doesn't have it's own view!(*))
(*)remark as marked above, you best do this only when the item you want to bind to does not have it's own view, if you have a view for your full page (an app view or something like that) you could bind the keyup in there, and just raise an event
App.trigger('keypressed', e);
for example.you can then in your EntryShow view, bind to that App's
keypressed
event.keep in mind that you should do something as a delayed event or grouping keypresses together in some situations, as firing every keypress that happens in the body, might be a big performance hit. especially on older browsers.
您的事件的范围将限于您的视图元素
@el
。要捕获文档
上的事件,您必须自己进行操作:应该可以解决问题。
Your events will be scoped to your view element
@el
. To capture events on thedocument
, you have to roll that yourself:Should do the trick.