【问题标题】:Backbone.js + Rest. Collection is not populated after fetch()Backbone.js + 休息。 fetch() 后未填充集合
【发布时间】:2011-11-07 18:02:19
【问题描述】:

我是 Backbone 的新手。所以我正在尝试从 REST 服务中获取数据。

这是我的简单代码:

$(function () {

    var Entity = Backbone.Model.extend({
        url: function() {
            return 'http://localhost:8080/rest/entity/'+this.id;
        }
    });

    var EntityList = Backbone.Collection.extend({       
        model: Entity,
        url: 'http://localhost:8080/rest/entity'
    });

    var entityList = new EntityList();

    entityList.fetch();

});

我的休息服务返回下一个 JSON:

[{"id":1387,
  "version":3,
  "entityName":"entity01",
  "entityLabel":"Entity01",
  "entityPluralLabel":"Entity01",
  "attributes":
     [{"id":1425,
       "slot":"D001",
       "version":0,
       "attributeName":"dfield",
       "attributeType":
          {"id":7,
           "description":"Date",
           "attributeType":"date",
           "databaseType":"DATE"
          },
       "options":[],
       "order":2,
       "attributeLabel":"dField",
       "checked":null
      },
      {"id":1424,
       "slot":"S001",
       "version":0,
       "attributeName":"txfield",
       "attributeType":
          {"id":1,
           "description":"Textbox",
           "attributeType":"textbox",
           "databaseType":"STRING"
          },
       "options":[],
       "order":1,
       "attributeLabel":"txField",
       "checked":null
      }
     ]  
 },
 {"id":1426,
  "version":3,
  "entityName":"entity02",
  "entityLabel":"Entity02",
  "entityPluralLabel":"Entity02",
  "attributes":
     [{"id":1464,
       "slot":"D001",
       "version":0,
       "attributeName":"dfield",
       "attributeType":
          {"id":7,
           "description":"Date",
           "attributeType":"date",
           "databaseType":"DATE"
          },
       "options":[],
       "order":2,
       "attributeLabel":"dField",
       "checked":null
      }
     ]
 }
]

在调试器中,我看到请求已发送到 REST 服务并收到响应,我如何查看 entityList 集合是否填充了收到的数据?在 entityList.fetch(); 之后,在调试器中 entityList.models 为空;

我的方法是正确的还是我的代码有问题?

【问题讨论】:

  • backbone 的源代码非常简单。也许它有助于通过实际的主干源来查看发生了什么。

标签: rest backbone.js


【解决方案1】:

我认为你是在正确的方式。但是因为Backbone.Collection.fetch() 是异步的,所以你不应该在方法调用之后检查entityList.models 的值,而是在fetch 的success 回调中检查。

也就是说,这段代码会说模型列表是空的:

entityList.fetch();
console.log(entityList.models); // => 0 (collection being fetched)

虽然此代码将在填充集合时打印集合中的模型数量:

entityList.fetch({success: function(){
    console.log(entityList.models); // => 2 (collection have been populated)
}});

【讨论】:

  • 另外,考虑在集合上重载parse 函数。它会让您在响应到达时看到响应,并且我经常发现我想做的不仅仅是在那个时候填充对象。
  • 感谢您的回答。你是对的异步获取,我在调试过程中突然发现了这个:)
  • 这为我节省了数小时的故障排除时间。我想在获取后立即使用该集合,但它是空的。添加成功处理程序以获取允许正确填充集合。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-15
  • 2011-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-18
  • 1970-01-01
相关资源
最近更新 更多