0
作为Backbone.js的新手,我尝试开发SPA,其中包括Addy Osmani的“开发Backbone.js应用程序”。它的练习2(http://addyosmani.github.io/backbone-fundamentals/#exercise-2-book-library---your-first-restful-backbone.js-app)显示了如何使用集合视图来渲染每个集合对象的内部模型视图。然而,这个例子中的集合视图并没有带有它自己的html标记。因此,集合的模型与集合视图的DOM元素(在这里:'#books')相关联。我想使用自己的模板来首先渲染我的集合视图的html元素,比如说,一个简单的div,id =“the-plan”。问题是,“#the.plan”不能从内部模型视图中识别为元素属性。因此,内部视图根本不会呈现。没有错误消息,并且所有console.log都可以工作。代码看起来像这样:在集合视图内渲染模型视图不知道它的元素?
app.PlanItemView = Backbone.View.extend({
className: "plan-item",
template: _.template($("#plan-item-view-template").html()),
render: function(){
console.log("Rendering plan item view...");
this.$el.append(this.template(this.model.toJSON()));
return this;
}
});
app.PlanView = Backbone.View.extend({
el: ".main-panel",
id: "#the-plan",
template: _.template($("#plan-view-template").html()),
initialize: function(initialPlanItems){
console.log("Plan View initialized... Selector: " + this.id);
console.log("Incoming initial plan item data: " + _.first(_.values(_.first(initialPlanItems))));
this.collection = new app.MealPlan(initialPlanItems);
this.render();
},
// render plan by rendering each item in its collection
render: function() {
this.$el.append(this.template({
"myPlan": this.collection.each(function(item){
this.renderPlanItem(item);
}, this)
}));
return this;
},
// render a plan item by creating a PlanItemView and appending the
// element it renders to the plan's id-element ('#the-plan')
renderDish: function(item){
var planItemView = new app.PlanItemView({
model: item,
el: this.id
});
this.$("#the-plan").append(planItemView.render());
}
});
...
var planView = new app.PlanView(test_plan_items);
这里有什么问题?
这做的伎俩(几乎)。我只需要将'this.collection.models.each(function(item))'改成'this.collection.each(function(item))'。但是,我不知道为什么?有人可以评论这些代码吗? – Bunjip
你可以看一下文档http://backbonejs.org/#Collection-Underscore-Methods,所以当你调用'this.collection.each'时,你正在遍历集合模型。 –
是的,我已经有了这部分代码。但是,我指的是你的原始答案。我没有真正了解render()和renderPlanItem()函数中会发生什么...... – Bunjip