Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Backbone.js 主干模型.fetch返回数据,但不更新模型_Backbone.js - Fatal编程技术网

Backbone.js 主干模型.fetch返回数据,但不更新模型

Backbone.js 主干模型.fetch返回数据,但不更新模型,backbone.js,Backbone.js,从服务器获取模型时,我遇到了一个问题。我在chrome开发工具中看到了从服务器返回的正确JSON,但模型不会使用返回的值进行更新 var listtemplate = new ListTemplateModel.Model({id: id}); listtemplate.fetch(); var listtemplate=new ListTemplateModel.Model({id:id}); fetch(); 我在Chrome开发工具中看到了正确的数据。以下是从服务器返回的内容: { "

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

var listtemplate = new ListTemplateModel.Model({id: id}); listtemplate.fetch(); var listtemplate=new ListTemplateModel.Model({id:id}); 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" } { “标题”:“模板一”, “id”:“模板”, “步骤”:[ { “描述”:“我爱它”, “id”:1, “创建时间”:“2012-12-24T18:01:48.402Z” }, { “描述”:“这是垃圾!”, “id”:1, “创建时间”:“2012-12-24T18:01:48.402Z” } ], “创建时间”:“2012-12-24T18:01:48.402Z” } 但是控制台记录JSON只会显示默认值和在模型创建过程中传入的id

console.log(listtemplate.toJSON()); log(listtemplate.toJSON()); 这将返回:

{id: "template_one", title: "", steps: Array[0]} {id:“模板”,标题:,步骤:数组[0]} 我的模型如下所示(我使用的是Require.js,因此上面的模型已重命名为ListTemplateModel)

var模型=B.Model.extend({ 默认值:{ 标题:“”, id:0, 步骤:[] }, urlRoot:'xxx' }); 有什么想法吗

编辑
@阿穆利亚的回答让我走上了正确的道路,然后我发现了“然后”。希望这对遇到同样问题的人有所帮助:

listtemplate.fetch().then(function(){ //update the view }); listtemplate.fetch().then(函数()){ //更新视图
}); 原因可能是您没有等待提取完成。试试这个:

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

好极了!!似乎就是这样。那么我必须在成功回调中包含我的视图渲染内容吗?是的,你是对的。。您应该在
success
回调中渲染视图@阿穆利亚的回答让我走上了正确的道路,然后我发现了“然后”。希望这对遇到同样问题的人有所帮助
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!');
    }
});