【问题标题】:Backbone relational lazy loading骨干关系延迟加载
【发布时间】:2011-09-11 19:33:55
【问题描述】:

我将 Backbone 与我的 RESTful JSON API 一起使用,以创建一个适用于帖子及其 cmets 的应用程序。我一直在尝试让 Backbone Relational 工作,但在延迟加载时遇到了问题。

我加载了一个帖子列表,没有相关的 cmets。单击列表中的帖子时,我会打开一个视图,该视图会获取完整的帖子、包含的 cmets 并呈现它。

我有 2 个 Backbone.RelationModels、帖子和评论。与评论的帖子关系设置如下:`

relations: [{
            type: Backbone.HasMany,
            key: 'comments',
            relatedModel: 'Comment',
            includeInJSON: true, // don't include it in the exporting json
            collectionType: 'Comments'
        }]

现在我面临的问题是,一旦我检索到我的列表,关系就会被初始化,但它还不包含 cmets。我稍后通过它的 URI 获取模型来加载完整的数据。但是,关系似乎没有重新初始化,调用 Posts.get(1).get('cmets') 返回一个空的 Comments 集合!

有谁知道我怎样才能最好地解决这个问题?数据在那里,只是 cmets 的集合似乎没有更新。

编辑:我可以让 Post 模型将它的 change:cmets 绑定到自身,从而更新集合。但是,我似乎找不到可靠的方法来获取原始 cmets 的 JSON,因为 this.get('cmets') 返回 Comments 集合。

注意:在我的集合中,我使用以下代码解析 JSON 以使其与我的 API 一起使用:

parse: function(response) {
        var response_array = [];
        _.each(response, function(item) {
            response_array.push(item);
        });

        return response_array;
    }

这是因为我的 API 返回的 JSON 返回带有索引键(关联数组)的对象,而不是原生 JSON 数组。

{
    "id" : "1",
    "title" : "post title",
    "comments" : {
        "2" : {
            "id" : "2",
            "description": "this should solve it"
        },
        "6" : {
            "id" : "6",
            "description": "this should solve it"
        }
    }
}

非常感谢!请提出任何问题,我确定我在某个地方含糊不清!

【问题讨论】:

    标签: javascript backbone.js backbone-relational


    【解决方案1】:

    主干关系模型不解析数组以外的集合,我的问题中的 JSON 不起作用。我更改了后端以在适当的数组中返回 cmets

    {
        "id" : "1",
        "title" : "post title",
        "comments" : [
            {
                "id" : "2",
                "description": "this should solve it"
            },
            {
                "id" : "6",
                "description": "this should solve it"
            }]
        }
    }
    

    RelationalModel 不尊重 Backbone 提供的解析函数,用于在继续之前解析您的 JSON。随着后端返回“正确”的 JSON,延迟加载无需任何额外代码即可工作。

    【讨论】:

      【解决方案2】:

      您还可以在评论模型上使用 initialize 方法,以模拟 parse 方法并使用自定义值定义属性,如下所示(CoffeeScript):

      initialize: (obj) ->
        @attributes = obj.customKey 
      

      【讨论】:

        猜你喜欢
        • 2023-03-05
        • 2014-01-29
        • 2013-12-05
        • 1970-01-01
        • 1970-01-01
        • 2019-07-11
        • 2019-10-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多