Search code examples
javascriptbackbone.jstastypie

Backbonejs collection returns wrong data


I'm using Tastypie for my RESTful api and Backbonejs for front end. the fetch with models works fine, however, with Backbone.Collection I seem to get the wrong response:

_byCid: Object
  _byId: Object
  _callbacks: Object
  _onModelEvent: function () { [native code] }
  _removeReference: function () { [native code] }
  length: 1
  models: Array[1]
       0: d
       _callbacks: Object
       _changed: false
       _changing: false
       _escapedAttributes: Object
       _previousAttributes: Object
       attributes: Object
           cid: "c14"
           collection: d
               __proto__: o
               length: 1
               __proto__: Array[0]
               __proto__: o

Here is my collection :

define(
[
    'models/ad',
],
function(AdModel){
    return Backbone.Collection.extend({
        url: '/api/v1/ad',
        model: AdModel,

        initialize: function(){
            this.fetch({
                success: function(coll, resp){
                    console.log(coll);
                }
            });
        }
    });
}

);

And here is my Model:

   define(
[],
function(){
    return Backbone.Model.extend({

    });
}

);


Solution

  • All what I had to change was my Collection.parse method.

    define(
       [
         'models/ad',
       ],
    function(AdModel){
       return Backbone.Collection.extend({
          url: '/api/v1/ad',
          model: AdModel,
          parse: function(data){
              return data.objects;
          },
          initialize: function(){
            this.fetch({
                success: function(coll, resp){
                    console.log(coll);
                }
            });
        }
      });
    }
    

    and everything worked fine.