Search code examples
objectcollectionsbackbone.js

Getting Data From Backbone Collection Fetch()


I'm relatively new to Backbone, and I'm trying to pass data back and forth between my server-side code. I have a collection setup:

var AppCollection = Backbone.Collection.extend({

    model: AppModel,

    url: 'data.php'

});

And then in my view I have my initialize pulling:

initialize: function(){
    items = this.collection.fetch();
    console.log(items);
}

Which outputs the items object. I've tried console.log(items.responseText) to just print out the contents of the returned JSON but I'm getting undefined.

Here's what I'm seeing in my console with console.log(items):

enter image description here

My goal is just to output that responseText. Any ideas?


Solution

  • As the backbone documentation says .fetch() returns a jQxhr object.

    There are two possible ways to achieve, either you can write success and error callbacks to the fetch like this:

    this.collection.fetch({
      success : function(collection, response) {
        // code here
      },
    
      error : function(collection, response) {
        // code here
      }
    });
    

    Or you can bind an event to reset method of the collection which is fired after the collection is successfully loaded.

    this.collection.bind("reset", method_name);
    

    You can access the collection on the method_name, as it will be executed after the fecth() ajax is executed. But I would suggest to use the first way as the second has its own other use cases.