如何使用 Backbone 将多条记录呈现到 html 表中.js .

How do I render multiple records out to a html table with Backbone.js ?

本文关键字:html 表中 js 记录 Backbone 何使用      更新时间:2023-09-26
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 的开发者工具。如果我在渲染函数内部做一个控制台.log(this.model(,我可以看到一个对象的混乱,其中两个记录存储在.attributes中。但是我没有在表中添加两行,而是得到 7。其中 6 个是对象。(虽然我在 Chrome 的控制台中看到 9 个子对象(。

这对我来说没有多少意义。谁能帮助我不仅使它工作,而且理解它?我知道 render(( 会在我实例化 cView 后立即触发,并且我知道一旦我在模型中执行 .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();