在打印<%console.log(Model.id)%>时,下划线模板不会加载Model.id。它是未定义的

时间:2014-07-13 19:02:51

标签: javascript backbone.js underscore.js

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

1 个答案:

答案 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方法以重命名该属性,但在尝试将数据发送回服务器时会导致问题。