我正在尝试使用骨干关系实现Backbone。
索赔模型:
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个Claim模型,每个Claim模型在属性键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”),它会显示输出[object Object]
我只是在学习Backbone,所以任何指针都会受到赞赏。
答案 0 :(得分:2)
你不应该在模板中使用get
- Underscore模板可以使用JSON,而不是Backbone模型对象(使用template(model.toJSON())
将模型传递给模板),因此应该对它们进行评估使用基本的点符号:
<tr>
<td><%= item.id %></td>
<td><%= item.promotion_id %></td>
</tr>