如何在主干视图中绑定/取消绑定窗口事件

San*_*ing 2 coffeescript backbone.js backbone-views

我需要在主干视图内的窗口对象上绑定事件,当导航到其他主干视图时,我想取消绑定窗口事件。有没有什么有效的方法可以在主干中做到这一点?

例子:

class Example.Views.EntriesList extends Backbone.View

  initialize: ->

    $(window).unbind('scroll').on 'scroll', _.bind(@scroll, this)
Run Code Online (Sandbox Code Playgroud)

上面的代码非常适合这个视图,但是当导航到不同的主干视图时,滚动绑定仍然存在。我想在视图更改时删除绑定到窗口的所有事件。

mu *_*ort 5

你真的应该View#remove在忘记它之前打电话来清理视图。所以你应该有remove这样的看法:

remove: ->
    $(window).off('scroll')
    super()
Run Code Online (Sandbox Code Playgroud)

请记住,当您将所有侦听器解除绑定到'scroll'事件window时,您$(window).off('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')
Run Code Online (Sandbox Code Playgroud)

防止您的视图干扰应用程序的其他部分。