0

在我的应用程序中,我已经到了无法决定应该使用哪种类型的 JSON 结构的地步。我的应用程序有多个嵌套视图,如下所示 -

-pageView
    -sectionView
        -articleView
            -widgetView
    -sectionView
        -articleView
            -widgetView
            -widgetView
        -articleView
            -widgetView

目前我正在使用单个 JSON 文件,其中包含一个中的所有 pageViews 和另一个中的所有 sectionViews ......等等。这是因为我严重依赖 Backbone Collections 来对模型进行排序并渲染每个视图。但显然,对于这种类型的结构,我只为页面视图进行了大约四次获取。(这甚至不是我的所有应用程序)。我在我的应用程序开始时获取所有这些,因为它们是搜索工具和显示完成状态所需要的。每个模型都知道它的父级,这就是它能够插入到父级容器中的方式。

另一方面,我可以使用一个包含所有内容的大型嵌套 JSON 文件,看起来像这样:

{
    "page":"page_05",
    "title":"Title of page",
    ...
    "sections":[
        {
            "section":"section_05",
            "title":"section title",
            "articles":[
                {
                    "article":"article_05",
                    "title":"article title",
                    "widgets":[
                        {
                            "widget":"widget_05",
                            ...
                        }

                    ]
                }
            ]
        },
        {
            "section":"section_10"             
            ...
        }

    ]

我不介意以哪种方式构建它,因为我可以简单地将数据放入集合中。如果我使用单个 JSON 文件,当 Backbone fetch 已经执行此操作时,必须编写将执行此操作的函数似乎有点奇怪。我想我要问的是......以前有没有人遇到过这个问题,解决方案是什么?一如既往地欢迎任何想法或演示。提前致谢。

4

1 回答 1

2

If I can try and generalize, your issue is that the ideal data format (one giant response) doesn't seem to fit Backbone's scheme of using fetch on models and collections. This is not an uncommon problem with Backbone, and so Backbone has a solution built-in: parse.

Both Backbone.Collection and Backbone.Model have a parse method, which by default does nothing. However, you can override it to add custom response handling of whatever comes back from a fetch call, eg.:

parse: function(originalGiantResponse) {
    someModel.set(originalGiantResponse.someModelPart);
    someCollection.add(originalGiantResponse.someCollectionPart);
    return originalGiantResponse.mainPart; // use the "mainPart" of the response
}

By using one or more parse overrides you should be able to use any structure for your server-side JSON that you want, and still make it fit any client-side Backbone code structure you want.

于 2013-04-26T21:14:01.217 回答