0

stories.json有:

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

这是我的 Backbone 应用程序示例:

(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);

我应该在哪里以及如何展平 Backbone 中的 stories.json 数组以获取 List 集合?

4

1 回答 1

0
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();
于 2013-04-02T15:00:49.170 回答