我一直在阅读有关backbone.js 中嵌套视图的大量内容,并且了解其中的很多内容,但仍然令我困惑的一件事是……
如果我的应用程序有一个 shell 视图,其中包含页面导航、页脚等子视图,这些子视图在使用应用程序的过程中不会改变,那么我是否需要为每个路由渲染 shell,或者我是否需要执行某种操作检查视图以查看它是否已经存在?
在我看来,如果有人在应用程序中前进之前没有点击“主页”路线,就会出现这种情况。
我在谷歌搜索中没有发现任何对此有帮助的信息,所以任何建议都是值得赞赏的。
Thanks!
由于您的“shell”或“布局”视图永远不会改变,因此您应该在应用程序启动时渲染它(在触发任何路由之前),并渲染更多视图into布局视图。
假设您的布局如下所示:
<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
)用于渲染“顶级”视图,并确保前一个元素是remove
d 在新的渲染之前。如果您需要更改视图的呈现方式,这也可能会派上用场。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)