我应该在哪里平数组的项目收集骨干

Where should I flatten array of items for collection in Backbone?

本文关键字:项目 在哪里 数组 我应该      更新时间:2023-09-26

stories.json上我有:

[
    {
      id: '1',
      project_id: '2',
      current_state: 'finished',
      description: 'Description 1'
    },
    {
      id: '2',
      project_id: '2',
      current_state: 'finished',
      description: 'Description 2'
    },
]

这是我的骨干应用程序的例子:

(function($){
    var Item = Backbone.Model.extend({
    defaults: {
      id: '1',
      project_id: '2',
      current_state: 'finished',
      description: 'Description'
    }
  });  
  var List = Backbone.Collection.extend({
    url: 'stories.json',
    model: Item
  });
  var ListView = Backbone.View.extend({
    el: $('body'),
    events: {},
    initialize: function(){
      _.bindAll(this, 'render', 'appendItem'); // remember: every function that uses 'this' as the current object should be in here
      this.collection = new List();
      this.collection.fetch();
      this.render();      
    },
    render: function(){
        var self = this;      
      $(this.el).append("<ul></ul>");
      console.log(this.collection)
      _(this.collection.models).each(function(item){ // in case collection is not empty
        self.appendItem(item);
      }, this);
    },
    appendItem: function(item){
      $('ul', this.el).append("<li>"+ "ID: " +item.get('id')+"  "+item.get('description')+"</li>");
    }
  });
  var listView = new ListView();
})(jQuery);

我应该在哪里以及如何平那些故事。json数组在主干获取列表集合?

var ListView = Backbone.View.extend({
    ...
    initialize: function() {
        this.collection.on('reset', this.render, this);
    }
    ...
});
var // create collection
    list = new List(),
    // create view
    listView = new ListView({
        el: $('body'),
        collection: list
    });
list.fetch();