Backbone.js +rest。 fetch()后不会填充集合

我是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(); }); 

我的rest服务返回下一个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 } ] } ] 

在debugging器中,我看到请求被发送到REST服务和响应收到,我怎么能看到entityList集合是否填充接收数据? 在debugging器中entityList.models在entityList.fetch()后是空的。

我正确的方式或somthing是错误的我的代码?

我想你是对的。 但是因为Backbone.Collection.fetch()是asynchronous的,所以你应该在方法调用后不正确地检查entityList.models值,而是在successcallback中取回。

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

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

而这个代码将在已经填充时在集合中打印多个模型:

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