var ContractModel = Backbone.Model.extend({
    url:  "${g.createLink(controller:'waiverContract', action:'index')}"
})

var contract = new ContractModel({});
contract.fetch();
var contracts = new Backbone.Collection.extend({
    model: contract
});

var ContractView = Backbone.View.extend({
    initialize: function(){
        this.render();
    },
    render: function() {
        var root = this.$el;
        _.each(this.model, function(item) {
            var row = '<tr><td>' + item + '</td></tr>';
            root.find('tbody').append(row);
        });
        return this;
    }
});

var cView = new ContractView({ model: contract, el: $('#contracts') });


我打开了Chrome的开发人员工具。如果我在render函数中执行console.log(this.model),我会看到一个混乱的对象,其中两个记录存储在.attributes中。但是我没有得到两行,而是得到了7。其中有6行是对象。 (尽管我在Chrome的控制台中看到9个子对象)。

这对我来说意义不大。任何人都可以帮助我不仅使它起作用,而且还理解它?我知道我实例化cView后就会立即渲染render(),而且我知道只要将.fetch()放入模型中,它就会执行ajax。但这就是我所能理解的极限。

最佳答案

您应该获取并迭代集合,而不是模型。模型是一个“事物”,而一个集合就是许多“事物”。假设您要在模型中获取JSON格式的数组,则该数组将最终具有“ 1”,“ 2”等属性,并且这些属性中的每一个将只是普通的Javascript对象,而不是ContractModel实例。

这是重组代码的方式:

var ContractModel = Backbone.Model.extend();
var ContractCollection = Backbone.Collection.extend({
  //ContractModel class, not an instance
  model: ContractModel,
  //Set the url property on the collection, not the model
  url:  "${g.createLink(controller:'waiverContract', action:'index')}"
})

var ContractView = Backbone.View.extend({
  initialize: function(){
    //Bind the collection reset event, gets fired when fetch complets
    this.collection.on('reset', this.render, this);
  },
  render: function() {
    //This finds the tbody element scoped to your view.
    //This assumes you have already added a tbody to the view somehow.
    //You might do this with something like
    //this.$el.html('<table><tbody></tbody></table>');
    var $tbody = this.$('tbody');
    this.collection.each(function(contract) {
      //Add any other contract properties here,
      //as needed, by calling the get() model method
      var row = '<tr><td>' + contract.get('someContractProperty') + '</td></tr>';

      //Append the row to the tbody
      $tbody.append(row);
    });
    return this;
  }
});

//Instantiate collection here, and pass it to the view
var contracts = new ContractCollection();
var cView = new ContractView({
  collection: contracts,
  el: $('#contracts')
});
//Makes the AJAX call.
//Triggers reset on success, and causes the view to render.
//Assumes a JSON response format like:
// [ { ... }, { ... }, ... ]
contracts.fetch();

07-24 19:28