doremi
doremi

Reputation: 15329

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

I have a collection which I know is fetching the entire collection, but how do I get access to the data returned from the 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 (Shortened for brevity.)

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

Upvotes: 0

Views: 77

Answers (2)

Sathya
Sathya

Reputation: 5308

Another way.

var that = this;

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

Upvotes: 0

Peter Lyons
Peter Lyons

Reputation: 146084

fetch is asynchronous. You must use the event binding style.

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

Upvotes: 1

Related Questions