2
votes

I need to bind event on window object inside backbone view and when navigated to other backbone view i want to unbind window event. Is there any efficient way to do this in the backbone??

example:

class Example.Views.EntriesList extends Backbone.View

  initialize: ->

    $(window).unbind('scroll').on 'scroll', _.bind(@scroll, this)

Above code works perfect for this view but when navigated to different backbone view then scroll bind is still present. I wanted to remove all the events binded to window when view changes.

2

2 Answers

5
votes

You're really supposed to be calling View#remove to clean up a view before forgetting about it. So you should have a remove like this in your view:

remove: ->
    $(window).off('scroll')
    super()

Keep in mind that you're potentially interfering with other code by unbinding all the listeners to the 'scroll' event on window when you $(window).off('scroll') and that might do more than you want. You'd be better off using namespaces:

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')

to keep your view from interfering with other parts of your application.

2
votes

Have a look, at this answer: Disposing of view and model objects in Backbone.js

If this is a common requirement in your application I suggest you to try Backbone.Marionette, which helps you in this and other ways

Backbone.Marionette.ItemView.extend({
  onClose: function(){
    // custom closing and cleanup goes here
  }
});

Reference