如何访问骨干集合的获取结果?

时间:2013-10-17 00:39:08

标签: javascript backbone.js

我有一个我知道正在获取整个集合的集合,但是如何访问从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
  });

2 个答案:

答案 0 :(得分: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;
});

答案 1 :(得分:0)

另一种方式。

var that = this;

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