2

I want to use BackboneJS for single page sites. The structure I am thinking of using is have a div#pageWrapper for loading views into

# a simple example view
class View1 extends Backbone.View
    render: ->
        @$el.html @template()


class AppRouter extends Backbone.Router
    routes:
        "": "home"
        "view1": "view1"
        "view2": "view2"

    home: ->
        # init, render, attach to body. repeat for other controller actions
        view = new HomeView()
        view.render()
        $("#pageWrapper").html view.el

Is the the usual way of doing this? Or is there some kind of design pattern alreay available? I havent handled the clean up, do I need it? Or is it a side effect of simply replacing the page wrappers' html?

4

2 回答 2

3

Yes, you definitely need to handle closing of views and removing of them properly. If you don't, you'll end up with memory leaks and "zombie" views - views that should be dead, but aren't.

I've written about it extensively:

http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/

http://lostechies.com/derickbailey/2011/12/12/composite-js-apps-regions-and-region-managers/

The gist of it is that you should manage cleaning up your view within your view directly, and then use a standardized process to call your view's cleanup method.

For example, I use an object to show / remove / replace my views on the screen:


Region = (function (Backbone, $) {
    var currentView;
    var el = "#mainregion";
    var region = {};

    var closeView = function (view) {
        if (view && view.close) {
            view.close();
        }
    };

    var openView = function (view) {
        view.render();
        $(el).html(view.el);
        if (view.onShow) {
            view.onShow();
        }
    };

    region.show = function (view) {
        closeView(currentView);
        currentView = view;
        openView(currentView);
    };

    return region;
})(Backbone, jQuery);

Just be sure your view has a close method in it, and this code will clean it up for you. A simple close implementation would look like this:


Backbone.View.prototype.close = function(){
  this.remove();
  this.unbind();
  if (this.onClose){
    this.onClose();
  }
}

and now all of your views have this close method.

See the articles for more information.

于 2012-06-13T14:45:30.940 回答
0

Yes, the usual way of doing a single page site is to have some html-element within which you render the page to be shown at any given moment.

As for cleanup. You should clear the container element and within each View to be cleaned up, you should unbind all events concerning that view and if you're using for example ModelBinding, you should unbind that as well. So basically

Cleanup all subviews -> unbind events concerning this view -> clear html

Handling cleanup is important to avoid having ghost views and events messing things up.

于 2012-06-13T14:42:13.790 回答