【问题标题】:Backbone (Marionette) fetch in a collection returns an empty array (nested models)集合中的骨干(木偶)提取返回一个空数组(嵌套模型)
【发布时间】:2014-05-28 10:17:24
【问题描述】:

我正在使用 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 文件确定)并将其转换为主干集合。

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" } 
        ]
    }]
}]

我正在尝试使用来自data.json 的数据填充最顶层的集合(Organization)。

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

【问题讨论】:

    标签: backbone.js nested fetch


    【解决方案1】:

    解决了。必须确保

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      相关资源
      最近更新 更多