我正在尝试实现具有骨干关系的骨干。
声明模型:
define(['underscore', 'backbone', 'backbone-relational', 'models/User'], function(_, Backbone, relational, User) {
var Claim = Backbone.RelationalModel.extend({
relations: [{
type: Backbone.HasOne,
key: 'a_user',
relatedModel: User
}],
defaults: {
},
initialize: function() {
},
clear: function() {
this.destroy();
this.view.remove();
}
});
return Claim;
});
用户模型是重复的,但未设置任何关系。
下面是集合对象:
Object
_byCid: Object
_byId: Object
_callbacks: Object
currentPage: 1
firstPage: 1
information: Object
length: 3
models: Array[3]
0: Object
1: Object
_callbacks: Object
_deferProcessing: false
_escapedAttributes: Object
_isInitialized: true
_pending: Object
_permitsUsed: 0
_previousAttributes: Object
_queue: Object
_relations: Array[1]
_silent: Object
attributes: Object
_deleted: false
_new: false
a_user: Object
_callbacks: Object
_escapedAttributes: Object
_isInitialized: true
_pending: Object
_permitsUsed: 0
_previousAttributes: Object
_queue: Object
_relations: Array[0]
_silent: Object
attributes: Object
_deleted: false
_new: false
already_in_save: false
already_in_validation: false
coll_claims: Array[0]
coll_claims_partial: true
created_at: "2012-12-12 09:00:00"
email: "cloud.strife@test.com"
firstname: "Cloud"
id: 2
lastname: "Strife"
modified_at: "2012-12-12 09:00:00"
modified_columns: Array[0]
start_copy: false
title: "Mr"
validation_failures: Array[0]
virtual_columns: Array[0]
__proto__: Object
changed: Object
cid: "c4"
collection: undefined
id: 2
__proto__: Object
already_in_save: false
already_in_validation: false
created_at: "2012-12-12 09:00:00"
fulfilment: "bank"
id: 2
manual: 0
modified_at: "2012-12-12 09:00:00"
modified_columns: Array[0]
promotion_id: 1
purchase_id: 2
start_copy: false
status: "pending"
user_id: 2
validation_failures: Array[0]
virtual_columns: Array[0]
__proto__: Object
changed: Object
cid: "c3"
collection: Object
id: 2
__proto__: Object
2: Object
length: 3
因此,实质上集合中有 3 个声明模型,每个声明模型在属性键a_user都有一个嵌套的 User 模型。
模板如下所示:
<% _.each( claims, function( item ){ %>
<tr>
<td><%= item.get("id") %></td>
<td><%= item.get("promotion_id") %></td>
<td><%= item.get("a_user").get("firstname") %></td>
<td><%= item.get("purchase_id") %></td>
<td></td>
<td><%= item.get("status") %></td>
<td><%= item.get("created_at") %></td>
</tr>
<% }); %>
但是,这会导致错误:
TypeError: 'null' is not an object (evaluating 'item.get("a_user").get')
如果我把它带回 item.get("a_user"),它会显示输出 [对象对象]
我只是在学习骨干,所以任何指示都值得赞赏。
您不应该在模板中使用get
- 下划线模板适用于 JSON,而不是 Backbone 模型对象(您使用 template(model.toJSON())
将模型传递给模板),因此应使用基本的点表示法来评估它们:
<tr>
<td><%= item.id %></td>
<td><%= item.promotion_id %></td>
</tr>