我正在尝试将自定义属性添加到集合的每个项目中,但它不会显示在模板中。
我有很多引号都有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>
答案 0 :(得分:3)
这是因为实际更改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
。