2017-03-09 99 views
0

我創建一個模型來獲取用戶配置文件數據,然後使用它,但問題是每次它獲取數據(成功響應文本JSON可用)模型不更新。所以我必須手動設置它。這是我的代碼:骨幹JS模型提取不自動更新屬性

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')); 
}); 

有沒有更好的方法?還是我做錯了?

+0

也,你可以通過一個屬性哈希'set'設置多個屬性。 'usertest.set({userid:user.userid,full_name:user.full_name,/ * etc * /})'。 –

+0

甚至使用['_.pick'](http://underscorejs.org/#pick):'usertest.set(_。pick(user,'userid','full_name',/ * etc * /)) ;' –

回答

1

您需要從parse返回數據:

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

非常感謝 –