需要帮助了解骨干中嵌套视图的基础知识

时间:2013-03-07 17:54:35

标签: backbone.js backbone-views backbone-routing

我一直在做关于backbone.js中嵌套视图的一堆阅读,我理解了很多,但有一点让我感到困惑的是......

如果我的应用程序有一个包含页面导航,页脚等子视图的shell视图,这些子视图在使用应用程序的过程中没有改变,我是否需要为每个路径渲染shell或者我是在视图中进行某种检查以确定它是否已经存在?

如果有人在应用程序中前进之前没有点击“主页”路线,那对我来说似乎是这样。

我在google搜索中没有找到任何有用的信息,所以我们非常感谢您的建议。

谢谢!

1 个答案:

答案 0 :(得分:16)

因为你的" shell"或"布局"视图永远不会更改,您应该在应用程序启动时(在触发任何路径之前)渲染它,并将更多视图渲染到布局视图中。

让我们说你的布局看起来像这样:

<body>
  <section id="layout">
    <section id="header"></section>
    <section id="container"></section>
    <section id="footer"></section>
  </section>
</body>

您的布局视图可能如下所示:

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); 
  }
});

然后,您将在应用程序启动时设置布局:

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

在您的路由器代码中:

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());
  }
});

有很多方法可以为这只特殊的猫提供皮肤,但这是我通常处理它的方式。这为您提供了一个单一的控制点(renderChild),用于渲染您的&#34;顶级&#34;视图,并确保在呈现新元素之前前一个元素为remove d。如果您需要更改视图的呈现方式,这也可能会派上用场。

相关问题