从一个大的JSON文件获取

从一个大的JSON文件获取

本文介绍了主干多个集合,从一个大的JSON文件获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有更好的方法来创建多个集合,从一个大的JSON文件读取。我有一个JSON文件看起来是这样的。

I would like to know if any better way to create multiple collections fetching from a single big JSON file. I got a JSON file looks like this.

{
  "Languages": [...],
  "ProductTypes": [...],
  "Menus": [...],
  "Submenus": [...],
  "SampleOne": [...],
  "SampleTwo": [...],
  "SampleMore": [...]
}

我使用的URL /获取创建的每个集合上述JSON的每个节点。

I am using the url/fetch to create each collection for each node of the JSON above.

var source = 'data/sample.json';

Languages.url = source;
Languages.fetch();

ProductTypes.url = source;
ProductTypes.fetch();

Menus.url = source;
Menus.fetch();

Submenus.url = source;
Submenus.fetch();

SampleOne.url = source;
SampleOne.fetch();

SampleTwo.url = source;
SampleTwo.fetch();

SampleMore.url = source;
SampleMore.fetch();

此Any更好的解决方案?

Any better solution for this?

推荐答案

骨干是伟大的,当你的应用程序符合它提供模具。但是,不要害怕去解决它,当它是有道理的应用程序。这是一个非常小的图书馆。制作重复和重复的GET请求只适合骨干模具可能极其低效。请查看或你最喜欢的基本AJAX库,有一些基本的元编程如下配对:

Backbone is great for when your application fits the mold it provides. But don't be afraid to go around it when it makes sense for your application. It's a very small library. Making repetitive and duplicate GET requests just to fit backbone's mold is probably prohibitively inefficient. Check out jQuery.getJSON or your favorite basic AJAX library, paired with some basic metaprogramming as following:

//Put your real collection constructors here. Just examples.
var collections = {
    Languages: Backbone.Collection.extend(),
    ProductTypes: Backbone.Collection.extend(),
    Menus: Backbone.Collection.extend()
};

function fetch() {
    $.getJSON("/url/to/your/big.json", {
        success: function (response) {
            for (var name in collections) {
                //Grab the list of raw json objects by name out of the response
                //pass it to your collection's constructor
                //and store a reference to your now-populated collection instance
                //in your collection lookup object
                collections[name] = new collections[name](response[name]);
            }
        }
    });
}

fetch();

一旦你叫取()和ASYN回调已经完成,你可以做这样的事情 collections.Menus.at(0) 来得到在加载模型实例。

Once you've called fetch() and the asyn callback has completed, you can do things like collections.Menus.at(0) to get at the loaded model instances.

这篇关于主干多个集合,从一个大的JSON文件获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 06:00