javascript 使用子集合将 JSON 数据转换为骨干模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14444233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:39:56  来源:igfitidea点击:

Converting JSON data to Backbone Model with child Collection

javascriptjsonbackbone.js

提问by Sean Anderson

I am working with a Playlist object which has some properties defining itself as well as a PlaylistItem collection.

我正在使用一个 Playlist 对象,该对象具有一些定义自身的属性以及一个 PlaylistItem 集合。

When I receive data from my server, I get its JSON response in my client-side success method:

当我从我的服务器接收数据时,我在我的客户端成功方法中得到它的 JSON 响应:

success: function (data) {
    console.log("JSON data:", data);

    playlists = _.map(data, function (playlistConfig) {
        return new Playlist(playlistConfig);
    });

    ...
}

Here, I convert my JSON data into Playlist objects. Each Playlist object is a Backbone.Model.

在这里,我将我的 JSON 数据转换为播放列表对象。每个播放列表对象都是一个 Backbone.Model。

Here's how my data looks:

这是我的数据的外观:

enter image description here

在此处输入图片说明

And here's what the Playlist constructor looks like:

这是播放列表构造函数的样子:

return function(config) {
    var playlist = new Playlist(config);

    return playlist;
};

var Playlist = Backbone.Model.extend({
    defaults: function() {
        return {
            id: null,
            userId: null,
            title: 'New Playlist',
            selected: false,
            position: 0,
            shuffledItems: [],
            history: [],
            items: Backbone.Collection.extend({
                model: PlaylistItem
            })
        };
    },
    ...
}

My problem:

我的问题:

If I create a Playlist object with defaults, it initializes with an empty Backbone.Collection for PlaylistItem. However, if I create a Playlist object with an already-defined collection, I get a basic array and not a Backbone.Collection. This is because I am working with JSON data from the server which has not been converted to Backbone entities yet. That data is extended over the Playlist's defaults and overwrites the Backbone.Collection entity.

如果我使用默认值创建一个播放列表对象,它会使用一个空的 Backbone.Collection 初始化播放列表项。但是,如果我使用已定义的集合创建播放列表对象,则会得到一个基本数组,而不是 Backbone.Collection。这是因为我正在处理来自尚未转换为 Backbone 实体的服务器的 JSON 数据。该数据扩展到播放列表的默认值并覆盖 Backbone.Collection 实体。

What is a proper way to initialize with a populated Backbone.Collection? I could write code in Initializes which checks the type of my items array and if it is not a Backbone.Collection I could create a new Backbone.Collection and add the items to it and then replace the old array with the new one, but that seems really hoakey.

使用填充的 Backbone.Collection 进行初始化的正确方法是什么?我可以在 Initializes 中编写代码来检查我的 items 数组的类型,如果它不是 Backbone.Collection 我可以创建一个新的 Backbone.Collection 并将项目添加到其中,然后用新的替换旧的数组,但是看起来真的很虚伪。

采纳答案by georgedyer

Don't define your PlalistItems Collection inside defaults, but beforehand. Then, create an initialize method on your Playlist Model like so:

不要在默认值中定义您的 PlalistItems 集合,而是事先定义。然后,在您的播放列表模型上创建一个初始化方法,如下所示:

var PlaylistItems = Backbone.Collection.extend({
   ...
});

var Playlist = Backbone.Model.extend({
    initialize: function() {
        this.set('items', new PlaylistItems(this.items));
    },

    defaults: function() {
        return {
            id: null,
            userId: null,
            title: 'New Playlist',
            selected: false,
            position: 0,
            shuffledItems: [],
            history: [],
            items: []  // don't define your PlaylistItems Collection here
        };
}
});

Check out the fiddle here: http://jsfiddle.net/georgedyer/r2XKb/(you'll need to open the console to see the collection)

在此处查看小提琴:http: //jsfiddle.net/georgedyer/r2XKb/(您需要打开控制台才能查看集合)

回答by agaddie

Another issue I ran into was after you save your model to the server you will get back a response that will change your embedded collection into a regular javascript array. To remedy this I had to override the parse function on my model class like so:

我遇到的另一个问题是,在您将模型保存到服务器后,您将得到一个响应,该响应会将您的嵌入式集合更改为常规的 javascript 数组。为了解决这个问题,我必须像这样覆盖模型类上的解析函数:

var model = backbone.Model.extend({
        urlRoot : "/rest/model",

        initialize: function(){
            this.set("myCollection", new MyCollection(this.myArray));
        },

        defaults: {
            myArray: []
        },

        parse: function(response){
            this.set(response);
            this.set("myArray", new MyCollection(response.myArray));
        }
    });