Backbone.js 如何在主干视图中绑定/取消绑定窗口事件
我需要在主干视图中绑定窗口对象上的事件,当导航到其他主干视图时,我希望解除绑定窗口事件。在主干网中有没有有效的方法来实现这一点 例如:Backbone.js 如何在主干视图中绑定/取消绑定窗口事件,backbone.js,coffeescript,backbone-views,Backbone.js,Coffeescript,Backbone Views,我需要在主干视图中绑定窗口对象上的事件,当导航到其他主干视图时,我希望解除绑定窗口事件。在主干网中有没有有效的方法来实现这一点 例如: class Example.Views.EntriesList extends Backbone.View initialize: -> $(window).unbind('scroll').on 'scroll', _.bind(@scroll, this) 上面的代码非常适合这个视图,但当导航到不同的主干视图时,滚动绑定仍然存在。当视
class Example.Views.EntriesList extends Backbone.View
initialize: ->
$(window).unbind('scroll').on 'scroll', _.bind(@scroll, this)
上面的代码非常适合这个视图,但当导航到不同的主干视图时,滚动绑定仍然存在。当视图更改时,我想删除绑定到窗口的所有事件。看看这个答案: 如果这是应用程序中的常见要求,我建议您尝试一下,这在这方面和其他方面都会对您有所帮助
Backbone.Marionette.ItemView.extend({
onClose: function(){
// custom closing and cleanup goes here
}
});
你真的应该在忘记之前打电话来清理一个视图。因此,在您的视图中应该有这样一个
remove
:
remove: ->
$(window).off('scroll')
super()
请记住,当您$(window.off('scroll')
时,您将窗口上的'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')
以避免视图干扰应用程序的其他部分