我是Backbone的新手。这是我的模特:
window.Image = Backbone.Model.extend({
defaults: {
id: "",
url: ""
}
});
window.ImageCollection = Backbone.Model.extend({
model: Image
});
window.TargetDemoGraphic = Backbone.Model.extend({
defaults: {
targetDemographicId: "",
targetDemographicDescription: "",
checked: false
}
});
window.TargetDemoGraphicCollection = Backbone.Collection.extend({
model: TargetDemoGraphic,
url: ServiceUrl + "/targetDemoGraphic/getAll"
});
window.Promotion = Backbone.Model.extend({
url: function() {
return ServiceUrl + "/promotion/get/" + encodeURIComponent(this.id);
},
defaults: {
id: "",
item: Item,
start: "",
end: "",
title: "",
newPrice: "",
shortContent: "",
detailContent: "",
minLoyaltyPoint: "",
membershipRequired: "",
loyaltyPointRequired: "",
loyaltyPointExchangeRequired: "",
displayOnBanner: "",
images: ImageCollection,
bannerImage: Image,
targetDemoGraphics: TargetDemoGraphicCollection
}
}
window.PromotionCollection = Backbone.Collection.extend({
model: Promotion,
url: ServiceUrl + "/promotion/getAll"
});
我的问题是在模板中打印出嵌套集合targetDemoGraphics时,集合的长度始终为0。 我很困惑,因为嵌套的集合图像运行良好,它返回正确的值。
我的骨干观点:
window.PromotionReview = Backbone.View.extend({
initialize : function(options) {
_.bindAll(this, 'beforeRender', 'render', 'afterRender');
var _this = this;
this.render = _.wrap(this.render, function(render) {
_this.beforeRender();
render();
_this.afterRender();
return _this;
});
this.render();
},
beforeRender : function() {
},
render : function() {
var promotion = this.model.toJSON();
//promotion.targetDemoGraphics.length returns = 4
//promotion.images.length = 4
$(this.el).html(this.template(promotion));
return this;
}
});
模板:
<% if (targetDemoGraphics != null && targetDemoGraphics.length > 0) { %>
<% for (var idx in targetDemoGraphics) { %>
<p><%= targetDemoGraphics[i].label %></p>
<% } %>
<% } %>
// targetDemoGraphics.length = 0 ???
...
<% if (images != null && images.length > 0) { %>
<% for (var idx in images) { %>
<a href="<%=ServiceUrl + '/images/' + images[idx].url %>" data-gallery>
<img style="min-height:100px;height:100px;min-width:100px;width:100px;" src="<%=ServiceUrl + '/images/' + images[idx].url %>">
</a>
<% } %>
<% } %>
// images.length = 4,正确值???
当打印出促销时,我得到2个targetDemoGraphics,一个包含4个对象,另一个是函数???
答案 0 :(得分:0)
如果您正在嵌套集合,最好尝试使用一些Backbone扩展。检查Backbone Associations。使用某些扩展名可以帮助您绑定嵌套Models
和Collections
上的事件以及其他优势。