[英]How to bind/unbind window events in backbone view
我需要在骨架视图内的窗口对象上绑定事件,并且当导航到其他骨架视图时,我想取消绑定窗口事件。 在骨干网中有什么有效的方法吗?
例:
class Example.Views.EntriesList extends Backbone.View
initialize: ->
$(window).unbind('scroll').on 'scroll', _.bind(@scroll, this)
上面的代码非常适合该视图,但是当导航到其他主干视图时,滚动绑定仍然存在。 我想删除视图更改时绑定到窗口的所有事件。
您真的应该在忽略该视图之前调用View#remove
来清理该视图。 因此,在您的视图中应该有一个这样的remove
:
remove: ->
$(window).off('scroll')
super()
请记住,通过在$(window).off('scroll')
时将所有侦听器绑定到window
上的'scroll'
事件,可能会干扰其他代码,这可能会超出您的预期。 使用名称空间会更好:
initialize: ->
# The caller should have cleaned everything up so no need to `off` here.
$(window).on('scroll.EntriesList', _.bind(@scroll, @))
remove: ->
$(window).off('scroll.EntriesList')
# or .off('.EntriesList')
以防止您的视图干扰应用程序的其他部分。
看看这个答案: 在Backbone.js中处理视图和模型对象
如果这是应用程序中的常见要求,建议您尝试Backbone.Marionette ,它可以通过这种方式或其他方式为您提供帮助
Backbone.Marionette.ItemView.extend({
onClose: function(){
// custom closing and cleanup goes here
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.