expense.id在日志
中打印为未定义我的下划线模板
<% _.each(expenses, function(expense) { %>
<tr>
<td><%= expense.get('name') %></td>
<td><%= expense.get('amount') %></td>
<td><%= expense.get('category') %></td>
<td><% console.log(expense.id) %></td>
</tr>
<% }); %>
我的骨干视图
var ExpenseList = Backbone.View.extend({
el: '.page',
render : function(){
var expenses = new Expenses();
var that = this;
expenses.fetch({
success : function(expenses){
var template = _.template($('#expense-list-template').html(),
{expenses: expenses.models});
that.$el.html(template);
}
});
}
});
服务器响应
[
{
"_id": "53c25827555953000091ab71",
"name": "Shell",
"amount": "$1000",
"category": "Internet"
},
{
"_id": "53c2bfee4bf93700006fb714",
"name": "FC",
"amount": "$432",
"category": "Game"
}
]
答案 0 :(得分:1)
您的服务器正在发送_id
个属性,而不是id
属性。
最简单的选择是在您的模型上设置idAttribute
:
var Expense = Backbone.Model.extend({
idAttribute: '_id',
//...
});
var Expenses = Backbone.Collection.extend({
model: Expense,
//...
});
这将为您expense.get('_id')
和expense.id
提供相同的功能,模型会将_id
发送回服务器。
您还可以向模型添加parse
方法以重命名该属性,但在尝试将数据发送回服务器时会导致问题。