我在Backbone(Marionette)中使用嵌套模型和集合。
// Basic unit
Models.User = Backbone.Model.extend({});
Models.Users = Backbone.Collection.extend({ model: Models.User });
// A Group has a collection of Users
Models.Group = Backbone.Model.extend({
initialize: function() {
var users = new Models.Users(this.get("users"));
this.set("users", users);
}
});
Models.Groups = Backbone.Collection.extend({ model: Models.Group });
// An Organization has a collection of Groups
Models.Organization = Backbone.Model.extend({
initialize: function() {
var groups = new Models.Groups(this.get("groups"));
this.set("groups", groups);
}
});
Models.Organizations = Backbone.Collection.extend({
model: Models.Organization,
url: "./data/data.json"
});
我的理解是this.get
将返回一个对象数组(通过data.json
文件确定)并将其转换为Backbone Collection。
data.json
文件具有以下结构:
[{
"id": "org1",
"groups": [{
"id": "group1",
"users": [
{ "name": "Alice" },
{ "name": "Bob" }
]
},
{
"id": "group2",
"users": [{ "name": "Charlie" }]
}]
},
{
"id": "org2",
"groups": [{
"id": "groupA",
"users": [{ "name": "Eve" }]
},
{
"id": "groupB",
"users": [
{ "name": "Linda" },
{ "name": "Mallory" }
]
}]
}]
我尝试使用Organization
中的数据填充最顶层的集合(data.json
)。
在index.html
中,我有:
<script type="text/javascript">
$(document).ready(function() {
MyApp.OrgManager.addInitializer(function() {
var data = new MyApp.Models.Organizations();
data.fetch({
success: function(collection) {
console.log("Success", collection);
}
});
});
MyApp.start();
});
</script>
fetch返回成功,但我的控制台输出是一个空数组。什么地方出了错?
答案 0 :(得分:0)
解决了它。不得不确保
XMLHttpRequests
和_.bindAll
一些事情,以便this
有适当的背景。