保存我在其中创建集合的 Backbone 模型

Saving a Backbone model where i've created a collection inside

我有一个名为 'Playlist' 的模型,我从服务器返回,其中有一个名为 'videos' 的对象数组。当我从服务器获取 'Playlist' 数据时,我需要将 'videos' 变成一个集合。我有时会更新 'videos' 集合中的模型。现在我去保存'Playlist'模型的时候,会不会因为我把'videos'属性设置为一个Collection而出现问题?我是否需要在保存之前将其恢复为原始项目数组?

如果有人能给我关于这种情况的最佳模式的任何提示,那就太好了。也许我应该创建一个单独的集合并单独保留播放列表的 'video' 属性,当我去保存播放列表模型时,我可以用集合的原始副本覆盖播放列表的视频属性。

....will there be a problem because I've set the 'videos' attribute to a Collection?

是的,会有的。正如您所说,您需要在发送前序列化 collection 。

我认为最好的方法是有一个 属性,它是一个 Backbone Collection,与您的 videos 属性分开。您在 initializesync 上更新此 collection。

您将仅使用 videos 属性 来填充您的 collection。

我的建议是在您的 Playlist 模型中覆盖 Backbone 的 save 方法以序列化您的视频 collection。一旦你序列化你的collection你的手模型保存回Backbone保存方法。

Model.Playlist = Backbone.Model.extend({

    initialize: function(options){
        this.initializeVideoCollection();

        this.on('sync', this.initializeVideoCollection, this);
    },

    initializeVideoCollection: function(){
        this.videoCollection = new Collections.VideoCollection(this.get('videos'));
    },

    save: function(attrs, options){
        attrs = attrs || this.toJSON();

        attrs.videos = this.videoCollection.toJSON();

        options.attrs = attrs;

        return Backbone.Model.prototype.save.call(this, attrs, options);
    }

});

我对此的解决方案通常是根据需要公开集合。换句话说,您的模型应该仅在有人明确需要时才创建集合:

Model.Playlist = Backbone.Model.extend({

     getVideosCollection: function() {
         if (!this._videos) {
             this._videos = new Collections.VideoCollection(this.get('videos'));
             // If people will be making changes to the videos,
             // you can keep the local data synchronized easily.
             this.listenTo(this._videos, 'add change remove', this._updateVideos);
         }
         return this._videos;
     }

     // Method called when the externally-shared collection is
     // modified
     _updateVideos: function() {
         this.set('videos', this._videos.toJSON());
     }
});

这样,其余的 Backbone 解析和保存结构将保持不变。