如何访问主干集合的提取结果

How do I access a backbone collection's fetched results?

本文关键字:集合 提取 结果 何访问 访问      更新时间:2023-09-26

我有一个集合,我知道它正在获取整个集合,但是我如何访问从获取返回的数据?

/

js/views/idea.js

define([
  'jquery', 
  'underscore', 
  'backbone',
  'collections/ideas'
], function($, _, Backbone, IdeasCollection) {
  var IdeasView = Backbone.View.extend({
    el: $('#container'),
    render: function(){
      this.collection = new IdeasCollection();
      console.log( this.collection.fetch() ); // I can see data
      var data = {};
      var template = _.template( $('#ideasView').html(), data);
      $('body').removeClass().addClass('blog');
      this.$el.html( template );
    }
  });
  return IdeasView;
});
/

js/collections/ideas.js (为简洁起见,缩短。

  var IdeasCollection = Backbone.Collection.extend({
    url: '/api/ideas',
    model: IdeaModel
  });

fetch是异步的。必须使用事件绑定样式。

var IdeasView = Backbone.View.extend({
    initialize: function () {
      this.collection = new IdeasCollection();
      this.listenTo(this.collection, 'sync', this.render);
      this.collection.fetch();
    },
    render: function(){
      var template = _.template( $('#ideasView').html(), this.collection.toArray());
      $('body').removeClass().addClass('blog');
      this.$el.html( template );
    }
  });
  return IdeasView;
});

另一种方式。

var that = this;
this.collection = new IdeasCollection();
this.collection.fetch({success: function (){
    that.render();
}});