2
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 的开发者工具。如果我在渲染函数中执行 console.log(this.model),我可以看到一个对象的混乱,其中两个记录存储在 .attributes 中。但是,我没有将两行添加到表中,而是得到了 7 个。其中 6 个是对象。(虽然我在 Chrome 的控制台中看到了 9 个子对象)。

这对我来说没有多大意义。任何人都可以帮助我不仅让这个工作,而且理解它吗?我知道一旦我实例化了 cView,render() 就会触发,而且我知道一旦我将 .fetch() 放入模型中,它就会执行 ajax。但这就是我能理解的极限。

4

1 回答 1

2

您应该获取并迭代集合,而不是模型。模型是一个“东西”,一个集合有很多“东西”。假设您正在获取一个 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();
于 2012-09-07T18:02:09.160 回答