Backbone中的嵌套模型

时间:2013-10-15 13:14:53

标签: backbone.js

我是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,以便开始使用它。

提前致谢!

2 个答案:

答案 0 :(得分:0)

默认支持非常缺乏您需要单独获取每个嵌套模型的数据

等图书馆

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

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

可替代使用

答案 1 :(得分:0)

items.fetch();
 console.log(items.toJSON());

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

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

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

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