Search code examples
javascriptbackbone.jsbackbone-model

backbone fetching a model returning strange data


I am fetching model data from my server like this in my backbone application,

var projectModel = new App.Models.Project({ id: 1001 });
projectModel.fetch();

The fetch works and I get data back from the server, but the data is not in the format I would expects, a project is model that contains other models and collections, however what comes back from the server and into the model is like this,

{ project_name: "A Test Project" project_managers: Array[5], workers: Array[10] }

This means that everytime I do a fetch for a project I have to set each attribute that needs to be a model or a collection like this,

projectModel.set('workers', new App.Collections.Users(projectModel.get('workers')));

In my model I do have an initialise fnction where I do all this setting, but that seems to get ignored on a fetch.

Surely there is a better way to set my attributes on fetch than having to go through them individually?

If overdide the parse method in the model like so,

parse: function(response, options) {
  this.set('workers', new App.Collections.Users(response.workers));
}

This does indeed return workers as collection within the project model, but it ignores single attributes like name, so I would expect this to returned,

{
  name : Test Project,
  workers : s //this is how console.log outputs it
},

but all I get back,

{
    workers : s //this is how console.log outputs it
 }

why is this?


Solution

  • You could override your model parse method to implement this behavior to be executed automatically each time you fetch your model

    http://backbonejs.org/#Model-parse

    The function is passed the raw response object, and should return the attributes hash to be set on the model.

    So in your model

    parse: function(response, options) {
      response.workers = new App.Collections.Users(response.workers));
      return response;
    }