2015-02-23 56 views
0

我有一個名爲'Playlist'的模型,我從服務器返回了一個名爲'videos'的對象數組。當我從服務器獲取「播放列表」數據時,我需要將「視頻」轉換爲收藏集。我有時更新'視頻'集合中的模型。現在,當我去保存「播放列表」模型時,會出現問題,因爲我已將「視頻」屬性設置爲集合?在保存之前是否需要將其重新轉換爲原始數組項目?保存一個骨幹模型,我在裏面創建了一個集合

如果任何人都可以給我關於這種情況的最佳模式的任何提示,那將是好事。也許我應該創建一個單獨的集合並單獨保留播放列表的「視頻」屬性,當我去保存播放列表模型時,我可以用集合的原始副本覆蓋播放列表的視頻屬性。

回答

1

....會不會有問題,因爲我已將'videos'屬性設置爲 a Collection?

是的。如您所說,您需要在發送前序列化收集。

我認爲最好的辦法是有一個屬性是一個骨幹集合,分開你的videos屬性。您更新此集合initializesync

您將只使用videos屬性來填充您的收藏。

我的建議是在您的Playlist模型中重寫Backbone的save方法來序列化您的視頻集。一旦您序列化您的集合,您就可以將模型的保存返回到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); 
    } 

}); 
1

我對此的解決方案通常是根據需要公開集合。換句話說,你的模型應該只創建集合時,有人明確地需要它:

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()); 
    } 
}); 

這樣,你的主幹解析&儲蓄結構的其餘部分保持不變。