2
votes

I have this code in my Backbone application:

app.Collections.quotes = new app.Collections.Quotes();
app.Collections.quotes.fetch();

And I can see an array of Objects returned in the network tab but when I expand out the Collection, the Models array inside is 0. Do they get instantiated as Models when fetch() is ran on a new Collection?

This is my Collection:

app.Collections.Quotes = Backbone.Collection.extend({
  model: app.Models.Quote,
  url: function() {
    return app.Settings.apiUrl() + '/quotes';
  }
});

EDIT:

app.Collections.quotes.fetch({
        success: function(){
            app.Utils.ViewManager.swap('section', new app.Views.section({section: 'quotes'}));
        }
    });

And in my Model:

idAttribute: 'Number',

This was the fix! Thanks for help. Dan kinda pointed me in the right direction amongst the comments...

1
fetch should create the new model instances... do you have the data from the network tab and maybe some model code?Matt Zeunert
@Matt If the returned Objects don't have 'id' keys, I'm guessing the Collection Fetch() can't instantiate them as Models?benhowdle89
i assume you just console log right after fetching... wait for the collection reset event and then check itjakee

1 Answers

1
votes

Calling fetch() on a Collection attempts to populate the JSON response into Models: Collection#fetch.

Is your server definitely returning a valid JSON array of objects?

Do you have any validation on your Quote Model? I'm pretty sure Backbone validates each models before populating the collection, only populating with the models which pass. So if it exists, check that your Model#validate method is working correctly.

You shouldn't need an ID (although it's obviously required if you want to edit them).