Search code examples
backbone.js

Backbone JS model fetch not updating attributes automatically


I'm creating a model to fetch user profile data and then use it but the problem is every time it fetch for data (success response text JSON is available) the model doesn't updated. So I have to set it up manually. This is my code:

UserTest = Backbone.Model.extend({
  defaults: {
    userid: null,
    full_name: null,
    photo: null,
    sec_access: null
  },
  urlRoot: 'data/userprofile.php',
  parse: function (response) {
    if (response.photo == null || response.photo == '') response.photo ='images/default-usericon.png';
  }
});

var usertest = new UserTest;
usertest.fetch().then(function(user){
   usertest.set('userid',user.userid);
   usertest.set('full_name',user.full_name);
   usertest.set('photo',user.photo);
   usertest.set('sec_access',user.sec_access);
   console.log(usertest.get('userid'));
});

is there a better way? or am I doing it wrong?


Solution

  • You need to return the data from parse:

    parse: function (response) {
      if (response.photo == null || response.photo == ''){
        response.photo ='images/default-usericon.png';
      }
      return response; // This is very important
    }