Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone Model.fetch returns data but does not update model

Tags:

backbone.js

I am running into an issue when my Model is fetched from the server. I see the correct JSON returned back from the server in chrome dev tools but the model does not update with the returned values.

var listtemplate = new ListTemplateModel.Model({id: id});
listtemplate.fetch();

I see the correct data in Chrome dev tools at this point. Here is what comes back from the server:

{
  "title": "Template one",
  "id": "template_one",
  "steps": [
    {
      "description": "I love it",
      "id": 1,
      "created_at": "2012-12-24T18:01:48.402Z"
    },
    {
      "description": "This is rubbish!",
      "id": 1,
      "created_at": "2012-12-24T18:01:48.402Z"
    }
  ],
  "created_at": "2012-12-24T18:01:48.402Z"
}

but console logging the JSON show me just the default value and the id that was passed in during the model creation.

console.log(listtemplate.toJSON());

and this returns:

{id: "template_one", title: "", steps: Array[0]}
 

My model looks like this (I am using Require.js, hence the Model has been renamed to ListTemplateModel above)

var Model = B.Model.extend({
        defaults: {
            title: '',
            id: 0,
            steps: []
        },
        urlRoot: 'xxx'
    });

Any ideas?

Edit @Amulya's answer set me on the right track and then i discovered "then". Hope this helps someone running into the same issue:

listtemplate.fetch().then(function(){
   //update the view
});
like image 965
mithun_daa Avatar asked Dec 24 '12 20:12

mithun_daa


1 Answers

The reason maybe because you do not wait for the fetch to be completed. Try this:

var listtemplate = new ListTemplateModel.Model({id: id});
listtemplate.fetch({
    success: function() {
        // fetch successfully completed
        console.log(listtemplate.toJSON());
    },
    error: function() {
        console.log('Failed to fetch!');
    }
});
like image 182
Amulya Khare Avatar answered Sep 28 '22 07:09

Amulya Khare