我正在尝试向集合的每个项添加一个自定义属性,但它没有显示在模板中。
我有很多client_id的报价。现在,我希望通过client_id获取客户机,并将其添加到集合条目中。通常,当使用console.log检查填充对象时,它可以工作,但是它不会出现在模板中。
我就是这么试的:
sprocket.QuotationsView = Backbone.View.extend({
id: 'content-inner',
initialize: function(options) {
// instantiate Collection
this.collection = new Quotations();
// compile Handlebars template
this.tpl = Handlebars.compile(this.template);
},
render: function() {
var self = this;
var obj = this.el;
// get quotations and set data to handlebars template
$.when(this.collection.fetch()).then(function(quotations) {
$.each(quotations, function(i, quotation) {
var loadContact = new Contact({id: quotation.contact_id}).fetch();
$.when(loadContact).then(function(contact) {
quotations[i]['contact'] = contact;
});
});
$(obj).html(self.tpl(quotations));
// if response is empty (no quotations in database), set empty template
}, function() {
$(obj).html(self.tpl);
});
return this;
}
});我的模板如下所示:
<div>
{{#if .}}
{{#each .}}
{{number}} <!-- this works -->
{{contact}} <!-- this doesn't work -->
{{contact.name}} <!-- this doesn't work too -->
{{/each}}
{{/if}}
</div>发布于 2014-07-28 21:43:06
这是因为回调实际上改变了Quotation.attribute.contact中的数据(即。您的quotations[i]['contact'] = contact;行)是在获取模板呈现之后的Contact之后执行的。
$.each(quotations, function(i, quotation) {
var loadContact = new Contact({id: quotation.contact_id}).fetch();
// This is the callback that is being executed after the backend responds
$.when(loadContact).then(function(contact) {
quotations[i]['contact'] = contact;
});
});
// This is the template rendering which is before the server has time to respond
$(obj).html(self.tpl(quotations));相反,在获取所有Contacts并将其添加到Quotations之后,将呈现模板。
解决这个问题的快速方法是:
Contacts的循环。Contacts之后调用回调。这是个人观点,绝不是对这个问题的回答:我不喜欢后端的数据逻辑,也不喜欢同一个类中的视图呈现和逻辑。我使用Backbone.Marionette将View和Controller拆分到由事件松散耦合的两个不同实体中。只有Controller知道View,只有View知道DOM。
https://stackoverflow.com/questions/24936468
复制相似问题