Question

I believe that, somewhere along the way, my Backbone collections aren't storing their models correctly. I'm also using backbone-pageable to have paginated collections, and my backbone app is based on https://github.com/alessioalex/ClientManager and some backbone tutorials.

Basically, as I understand it, Backbone Collections should have a models attribute that is:

Object
  models: Array
    0: Object
      model
      model, etc

But mine seem to have the structure:

Object
  models: Array
    0: Object
      attributes: Object
        tasks: Array (from my server JSON response)
        total_match, etc (other variables for pagination)

So thus, in my templates I always have to use tasks[0].each rather than just tasks.each

This also means that, when adding models to the collection, they aren't added to the array of models in tasks, but instead Backbone created another array in models, such that it becomes:

Object
  models: Array
    0: Object
      attributes: Object
        tasks: Array (from my server JSON response)
        total_match, etc (other variables for pagination)
    1: Object
      (new model attributes)

This then means that my template code, searching for tasks[0] doesn't pick it up. It also means that for my collections, I can't use collection.get(id), it returns nothing - even when using correct IDs and with a specified IDAttribute for the model.

I'm a bit stumped.

Was it helpful?

Solution

It appears that your server is returning a tasks Array nested in the JSON response. In order for Backbone to know how to properly parse the JSON, you need to override the parse() method and tell it to use the tasks array as the source for your models.

var MyModel = Backbone.Model.extend({});    
var MyCollection = Backbone.Collection.extend({
        model: MyModel,
        parse: function(response) {
           //tell Backbone to turn each element in 'tasks' into an instance of MyModel
           return response.tasks;  
        }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top