Backbone(Marionette)在集合中获取返回一个空数组(嵌套模型)

时间:2014-05-25 01:54:41

标签: backbone.js nested fetch

我在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返回成功,但我的控制台输出是一个空数组。什么地方出了错?

1 个答案:

答案 0 :(得分:0)

解决了它。不得不确保

  1. 我在本地网络服务器上运行该页面,因为jQuery不喜欢null origin XMLHttpRequests
  2. 我必须_.bindAll一些事情,以便this有适当的背景。