【问题标题】:create a complex collection in backbonejs在backbonejs中创建一个复杂的集合
【发布时间】:2012-09-22 08:29:36
【问题描述】:

简而言之,我想对其他集合和模型进行骨干深度集合

结构是这样的

[{
    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
});

我的问题在这里我想在TopicCategories 上调用fetch 我想填充所有内容,fetch 将返回一个JSON 就像在示例中传递的那样,但是如果我在@987654328 上调用fetch @ 它会返回数据,但数组只是普通的 JavaScript 数组,而不是我在默认值中想要的骨干集合

【问题讨论】:

    标签: javascript backbone.js


    【解决方案1】:

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

    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;
    }
    

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

    此链接可能会为您提供更多关于这一切如何运作的想法。

    Dealing with nested collections

    【讨论】:

      猜你喜欢
      • 2018-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 2012-12-05
      • 1970-01-01
      • 2015-01-21
      • 2020-07-23
      相关资源
      最近更新 更多