0

我是 Backbone 的新手,我对嵌套模型有疑问。在这里,我有 data.json,其中有以下 JSON:

[
    {
        "name": "Project",
        "description" : "This is a Peugeot website",
        "url" : "http://peugeot.am",
        "images" : [
            { "image" : "A", "thumb" : "a" },
            { "image" : "B", "thumb" : "b" },
            { "image" : "C", "thumb" : "c" }
        ]
    },
    {
        "name" : "Ararat",
        "description" : "This is a Ararat website",
        "url" : "http://ararat.am",
        "images" : [
            { "image" : "A", "thumb" : "a" },
            { "image" : "B", "thumb" : "b" },
            { "image" : "C", "thumb" : "c" }
        ]
    },
    {
        "name" : "Procredit Bank",
        "description" : "This is a Procredit Bank website",
         "url" : "http://procredit.am",
        "images" : [
            { "image" : "A", "thumb" : "a" },
            { "image" : "B", "thumb" : "b" },
            { "image" : "C", "thumb" : "c" }
        ]
    }
]

在 Backbone 中,我试图获取数据,但我得到了空数组。

var myapp = myapp || {};

$(function () {

    myapp.Image= Backbone.Model.extend({
        initialize: function () {
            this.Img = this.get('image');
            this.Thumb = this.get('thumb');
        }
    });

    myapp.Images= Backbone.Collection.extend({ model: myapp.Image });

    myapp.Item= Backbone.Model.extend({
        initialize: function () {
            this.Name = this.get('name');
            this.Description = this.get('description');
            this.URL = this.get('url');
            this.subs = new myapp.Images(this.get('images'));
        }
    });

    myapp.Items= Backbone.Collection.extend({
        model:  myapp.Item,
        url: 'content/js/data.json',
        parse: function (resp, xhr) { return JSON.parse(resp); }
    });

    var items = new myapp.Items();
    items.fetch();
    console.log(items.toJSON());
});

现在,我在上面做错了什么?我需要获取数据以获取 JSON,以便开始使用它。

提前致谢!

4

2 回答 2

0

the default support is pretty lacking you would need to get the data for each nested model separately

There are library such as

https://github.com/powmedia/backbone-deep-model

and

http://afeld.github.io/backbone-nested/

Which can be used instead

于 2013-10-15T13:30:40.760 回答
0
items.fetch();
 console.log(items.toJSON());

Collection.fetch() 是一个异步操作。在请求从服务器返回之前,它不会产生响应。尝试这个:

items.fetch().done(function(){
    console.log(items.toJSON());
});

您还可以使用 safari/chrome(或 firefox 调试器/firebug)中的网络检查器来监控网络请求并查看您的调用是否成功触发(并检查响应),或者将另一个 console.log 语句放入“解析”函数中你的收藏。

http://backbonejs.org/#Collection-fetch

于 2013-10-15T13:41:34.413 回答