Backbone Model.fetch返回数据但不更新模型

mit*_*daa 6 backbone.js

当从服务器获取模型时,我遇到了一个问题.我在chrome dev工具中看到从服务器返回的正确JSON,但模型不会使用返回的值进行更新.

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

此时我在Chrome开发工具中看到了正确的数据.以下是从服务器返回的内容:

{
  "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"
}

但是控制台记录JSON只显示默认值和模型创建期间传入的id.

console.log(listtemplate.toJSON());

这会返回:

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

我的模型看起来像这样(我使用的是Require.js,因此模型已经重命名为上面的ListTemplateModel)

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

有任何想法吗?

编辑 @ Amulya的答案让我走上正轨,然后我发现了"然后".希望这可以帮助有人遇到同样的问题:

listtemplate.fetch().then(function(){
   //update the view
});

Amu*_*are 9

原因可能是因为您不等待获取完成.试试这个:

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!');
    }
});
Run Code Online (Sandbox Code Playgroud)