我在圈子里跑来跑去,似乎在我当前的应用程序中实施backbone.js中缺少一些东西。问题是我有一个主AppView,它初始化页面的各种子视图(图表,信息表等)。我的愿望是能够根据导航时传递的参数标志更改页面的布局。骨干视图嵌套
我碰到的情况是,在模板渲染后引用了dom元素的子视图在主AppView初始化过程中无法访问这些元素。所以主要的问题是如何确保适当的dom元素适用于每个事件绑定过程以正确设置?
如果我有一个事件绑定到我的LayoutView中的模型更改,则会显示布局,但后续视图无法正确呈现。我已经弄清楚的一些事情是将所有视图的'.el'值设置为html结构中的静态元素。这会使渲染发生,尽管这似乎脱离了利用'.el'提供的良好范围限制能力。
示例代码:
//Wrapped in jquery.ready() function...
//View Code
GraphView = Backbone.View.extend({ // init, model bind, template, supporting functions});
TableView = Backbone.View.extend({ // init, model bind, template, supporting functions});
LayoutView = Backbone.view.extend({
initialize: function() {
this.model.bind('change:version', this.render, this);
},
templateA = _.template($('#main-template').html()),
templateB = _.template($('#secondary-template').html()),
render: function() {
if ('main' == this.model.get('version')) {
this.el.html(this.templateA());
} else {
this.el.html(this.templateB());
}
},
});
MainView = Backbone.View.extend({
initialize: function() {
this.layoutView = new LayoutView({
el: $('#layoutContainer'),
model: layout,
});
this.graphView = new GraphView({
el: $('.graphContainer'),
model: graph
});
this.tableView = new TableView({
el: $('#dataTableContainer',
model: dataSet
});
},
});
// Model Code
Layout = Backbone.Model.extend({
defaults: {
version: 'main',
},
});
Graph = Backbone.Model.extend({});
dataSet = Backbone.Model.extend({});
// Router code...
// Fire off the app
AppView = new MainView($('#appContainer'));
// Create route, start up backbone history
HTML: 为简单起见我只是重新安排了两个布局之间的div。
<html>
<head>
<!-- include above js and backbone dependancies -->
</head>
<body>
<script type="text/template" id="main-template">
<div class="graphContainer"></div>
<div class="dataTableContainer"></div>
<div>Some other stuff to identify that it's the main template</div>
</script>
<script type="text/template" id="secondary-template">
<div class="dataTableContainer"></div>
<div>Rock on layout version two!</div>
<div class="graphContainer"></div>
</script>
<div id="appContainer">
<div id="nav">
<a href="#layout/main">See Layout One</a>
<a href="#layout/secondary">See Layout Two</a>
</div>
<div id="layoutContainer"></div>
</div>
</body>
</html>
感谢您对任何人都有的见解/意见。谢谢!
只是FYI,你的代码中有一堆拼写错误 - 假设它们是复制/粘贴问题,而不是实际的语法错误,是否安全? – nrabinowitz
责备复制/粘贴,基本的逻辑,希望仍然被传达。感谢您指出了这一点。 – aztechy