Need help understanding the basics of nested views in backbone

前端 未结 1 1892
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-09 08:14

I\'ve been doing a bunch of reading about nested views in backbone.js and I understand a good amount of it, but one thing that is still puzzling me is this...

If my appl

1条回答
  •  情深已故
    2021-02-09 08:27

    Since your "shell" or "layout" view never changes, you should render it upon application startup (before triggering any routes), and render further views into the layout view.

    Let's say your layout looked something like this:

    
      

    Your layout view might look something like this:

    var LayoutView = Backbone.View.extend({
      el:"#layout",
      render: function() {
        this.$("#header").html((this.header = new HeaderView()).render().el);
        this.$("#footer").html((this.footer = new FooterView()).render().el);
        return this;
      },
    
      renderChild: function(view) {
        if(this.child) 
          this.child.remove();
        this.$("#container").html((this.child = view).render().el); 
      }
    });
    

    You would then setup the layout upon application startup:

    var layout = new LayoutView().render();
    var router = new AppRouter({layout:layout});
    Backbone.history.start();
    

    And in your router code:

    var AppRouter = Backbone.Router.extend({
      initialize: function(options) {
        this.layout = options.layout;
      },
    
      home: function() {
        this.layout.renderChild(new HomeView());
      },
    
      other: function() {
        this.layout.renderChild(new OtherView());
      }
    });
    

    There are a number of ways to skin this particular cat, but this is the way I usually handle it. This gives you a single point of control (renderChild) for rendering your "top-level" views, and ensures the the previous element is removed before new one is rendered. This might also come in handy if you ever need to change the way views are rendered.

    0 讨论(0)
提交回复
热议问题