0

简而言之,我想对其他收藏和模型进行深度收集

结构是这样的

[{
    mainCategory: "Something"
    subCategories: [
        {
            category: "SomethgingElse",
            labs: [
            {
                id: 1,
                title: "Title",
                description : "Lorem ipsum dolor sit amet"
                availablelanguages: ["fr","en"]
            },
            {
                id: 2,
                title: "Another Title",
                description : "Lorem ipsum dolor sit amet",
                availablelanguages: ["fr","en"]
            }]
        },
        {
            category: "Testing",
            labs: [
            {
                id: 1,
                title: "ZZZZ",
                description : "Lorem ipsum dolor sit amet"
                availablelanguages: ["ar","en"]
            },
            {
                id: 2,
                title: "VVVVV",
                description : "Lorem ipsum dolor sit amet",
                availablelanguages: ["ar","en"]
            }]
        }

    ]
}]

我定义了一些集合和模型,如下所示

var Item = Backbone.Model.extend({
    defaults: {
        title : '',
        description: '',
        availableLangagues : []
    }
});
var Items = Backbone.Collection.extend({
    model: Item
});

var Category = Backbone.Model.extend({
    defaults: {
        categoryName: '',
        labsList: new Items()
    }
});
var Categories = Backbone.Collection.extend({
    model: Category
});
var TopCategory = Backbone.Model.extend({
    defaults: {
        topCategory: "",
        categories: new Categories()
    }
});
var TopCategories = Backbone.Collection.extend({
    model: TopCategory
});

fetch我的问题在这里我想调用TopicCategories我想填充所有内容,fetch它将返回JSON示例中传递的类似,但如果我调用它将返回数据,但数组将只是普通的 JavaScript 数组,而不是像我这样的骨干fetch集合TopCategories在默认值中通缉

4

1 回答 1

2

您要做的是利用您parse()的顶级模型的功能。在这个修改后的解析中,您所做的是从响应中梳理出不同的对象/数组,并将它们转换为您想要的集合。示例:parse()在 TopCategory 模型中。

parse: function(response) {

    if (response.subCategories){

        if (!this.subCategories) {
            this.subCategories = new Categories(response.subCategories);
        } else {
            this.subCategories.reset(response.subCategories);
        }

        delete response.subCategories;
    }

    return response;
}

您将在每个父模型的解析定义中执行此模式,这些父模型具有您想要解析出的某种主干集合。

这个链接可能会给你一些关于这一切如何运作的更多想法。

处理嵌套集合

于 2012-09-22T08:46:54.937 回答