Question

I am trying to view the collection i import from the service, using backbone on the client side, and python/flask as the service. When i make the GET request, i get the following data back:

{"entries": [{"Title": "my title 1", "Description": "My desc 1", "Info": "Info 1", "ids": 1}, {"Title": "my title 2", "Description": "My desc 2", "Info": "Info 2", "ids": 2}]}

But those entries are not showing on my page, even though i use fetch. This is my ListView code:

var app = app || {};

app.ContactListView = Backbone.View.extend({
 el: '#contacts',

initialize: function () {

    this.collection = new app.ContactList();
this.collection.fetch({reset: true});
    this.render();
this.listenTo( this.collection, 'reset', this.render );
},


render: function () {
    this.collection.each(function( item ){
    this.renderContact( item );
}, this );
},

renderContact: function ( item ) {
    var contactView = new app.ContactView({
        model: item
    });
    this.$('#ContactTable').append( contactView.render().el );
}
});

What might be the cause?

Was it helpful?

Solution

The reason is because your collection is expecting an array of models as it's response but your service is returning the array under entries. From the documentation

parse is called by Backbone whenever a collection's models are returned by the server, in fetch. The function is passed the raw response object, and should return the array of model attributes to be added to the collection.

To work around that you can simply override your parse method to return the array of models.

For example:

app.ContactList = Backbone.Collection.extend({
      //...
     parse: function (response) {
         return response.entries;
     } 
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top