Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone JS: How to clean up views when navigate to another url?

I have a Homeview that contains a few subviews on page, when I navigate to another page using the router, how can I clean existing views, and build new views for the page I want to navigate to?

This application has no model/collections, just views.

Thank you!

Part of the code:

Home = Backbone.View.extend({
    template: "static/js/templates/home.html",

    initialize: function() {
      _.bindAll(this);
      this.render();
    },

    render: function() {
      var view = this;

      // Fetch the template, render it to the View element and call done.
      namespace.fetchTemplate(this.template, function(tmpl) {
        view.el.innerHTML=tmpl();
        view.subRender();
      });

      return this;
    },
    subRender: function() {
      var view = this;
      var videoView = new Subview1({
        el: $('#wrapper1'),
        homeView: view
      });
      var timeView = new Subview2({
        el: $("#wrapper2")
      });
    }
 });
like image 549
user469652 Avatar asked Mar 31 '12 22:03

user469652


1 Answers

You could probably just use backbone's events mechanism to do this if you wanted.

You'd just need to create a global event router, and then have each of your views listen for a CloseView event. Then you just need to perform all your shutdown on receiving the CloseView event.

var dispatcher = _.clone(Backbone.Events)

Home = Backbone.View.extend({
    ...
    initialize: function() {
        ...
        dispatcher.on( 'CloseView', this.close, this );
    }
    close: function() {
        // Unregister for event to stop memory leak
        dispatcher.off( 'CloseView', this.close, this );
        this.remove();
        this.unbind();
        this.views = [];   // Clear the view array
    }
    ...
});

SubView = Backbone.View.extend({
    ...
    initialize: function() {
        ...
        dispatcher.on( 'CloseView', this.close, this );
    }
    close: function() {
        // Unregister for event to stop memory leak
        dispatcher.off( 'CloseView', this.close, this );
        // Do other close stuff here.
    }
});

Then it's just a case of calling dispatcher.trigger( 'OnClose' ) in your router/elsewhere to trigger the close functions.

As a shortcut, assuming you wanted to perform this shutdown on every navigation, you could just register for events on the router (either a custom 'OnClose' event as here, or the 'all' event to just get every navigation) though you would have to be careful that the events were called in the order you were expecting.

It'd also probably be possible to refactor some of this code into Backbone.View.prototype or similar, but I'll leave that for someone else to do.

like image 110
obmarg Avatar answered Oct 31 '22 19:10

obmarg