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

前端之家收集整理的这篇文章主要介绍了backbone.js – Backbone Model.fetch返回数据但不更新模型前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当从服务器获取模型时,我遇到了一个问题.我在chrome dev工具中看到从服务器返回的正确 JSON,但模型不会使用返回的值进行更新.
  1. var listtemplate = new ListTemplateModel.Model({id: id});
  2. listtemplate.fetch();

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

  1. {
  2. "title": "Template one","id": "template_one","steps": [
  3. {
  4. "description": "I love it","id": 1,"created_at": "2012-12-24T18:01:48.402Z"
  5. },{
  6. "description": "This is rubbish!","created_at": "2012-12-24T18:01:48.402Z"
  7. }
  8. ],"created_at": "2012-12-24T18:01:48.402Z"
  9. }

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

  1. console.log(listtemplate.toJSON());

这会返回:

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

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

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

有任何想法吗?

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

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

解决方法

原因可能是因为您不等待获取完成.试试这个:
  1. var listtemplate = new ListTemplateModel.Model({id: id});
  2. listtemplate.fetch({
  3. success: function() {
  4. // fetch successfully completed
  5. console.log(listtemplate.toJSON());
  6. },error: function() {
  7. console.log('Failed to fetch!');
  8. }
  9. });

猜你在找的JavaScript相关文章