我正在尝试从复杂的JSON对象创建一个html页面。我已经成功地解析JSON对象到模型的集合,其中每个模型都有的另一种模式等的集合..在Backbone.js中填充嵌套的下划线模板
因此我有嵌套的意见,以应付这一点。
要创建我的HTML页面,我有两个模板,如下所示:
<script type="text/template" id="template1">
<h1><%=heading1%></h1>
<h2><%=heading2%></h2>
<ul id="template2-list"></ul>
</script>
<script type="text/template" id='template2'>
<p class = "heading"><%-otherheading%></p>
<div class="content" id="tab">
.....
</div>
</script>
正如你所看到的,我有一个模板(模板1),它包含模板2的列表。我将如何去填充我的Backbone嵌套视图中的这些模板?
这是我曾尝试:
var CollectionView = Backbone.View.extend({
type: "CollectionView", //For debugging purposes
el: "#container",
initialize: function() {
},
render: function() {
_.each(this.model.models, this.process, this);
return this;
},
process: function(obj)
{
var childItemView = new View1({model: obj});
childItemView.render();
this.$el.append(childItemView.el); //This works fine since I only have one Model in the highest level collection
}
})
var View1 = Backbone.View.extend({
type: "View1",
template: _.template($("#template1").html()),
tagName: "div",
className: "tableRow",
initialize:function() {
this.model.on("change", this.modelChanged, this);
},
render: function() {
var outputHtml = this.template(this.model.toJSON());
this.$el.html(outputHtml);
this.model.get('nestedModel').each(this.process, this);
return this;
},
process: function(obj) {
var childItemView2 = new View2({model: obj});
childItemView2.render();
childItemView2.el = '#template2-list';
$(this.el).append(childItemView2.el); //This still results in template2 being placed after the entire template 1
},
modelChanged: function(model, changes) {
console.log("modelChanged: " + this.model.get('title'));
}
});
我从来没有想过按照您在第一个选项中所做的方式进行操作,但想要避免由于可能出现的可维护性问题。关于第二种选择,我是不是已经这样做了?我遍历父级集合中的所有模型,创建一个新的子视图实例。由于我有一个比这更复杂的情况,因此我在子视图中执行相同的操作,因为它在其模型中具有集合。我没有看到如何做到这一点将允许我嵌入在父视图模板的特定位置内的子视图呈现的内容? – Richard