0

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

/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
  });
4

2 回答 2

1

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;
});
于 2013-10-17T00:51:25.803 回答
0

另一种方式。

var that = this;

this.collection = new IdeasCollection();
this.collection.fetch({success: function (){
    that.render();
}});
于 2013-10-17T05:51:46.860 回答