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"
  }
]

最佳答案

您的服务器正在发回_id属性,而不是id属性。

最简单的选择是在模型上设置idAttribute

var Expense = Backbone.Model.extend({
    idAttribute: '_id',
    //...
});
var Expenses = Backbone.Collection.extend({
    model: Expense,
    //...
});


这将为您提供expense.get('_id')expense.id相同的内容,并且模型会将_id发送回服务器。

您也可以在模型中添加parse方法以重命名属性,但是在尝试将数据发送回服务器时会导致问题。

10-02 12:55