下划线模板不加载模型.% console.log(Model.id) %>它是未定义的

Underscore template does not load the Model.id, on printing the <% console.log(Model.id) %> it comes as undefined

本文关键字:未定义 id 加载 模型 下划线 log console Model      更新时间:2023-09-26

费用。Id在日志

中打印为未定义

My Underscore template

<% _.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>
<% }); %>

My Backbone View

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方法来重命名属性,但是当您试图将数据发送回服务器时,这会导致问题。