2014-02-05 129 views
0

我有一個主幹應用程序,它看起來像這樣:動態加載嵌套模型和集合骨幹

// Model for one picture 
var Picture= Backbone.Model.extend({ }); 

// Model for Collection of Pictures 
var Pictures = Backbone.Collection.extend({ model:Picture }); 

// Model for album 
var Album = Backbone.Model.extend(); 

//Model for a collection of Albums 
var Albums = Backbone.Collection.extend({ model:Album }); 

我的服務器支持以下功能

List<Album> GetAlbums(List<Guid> albumIds); 
List<Picture> GetPictures(albumId); 
Dictionary<string, string> GetAlbumMetadata(albumId); 
Dictionary<string, string> GetPictureMetadata(pictureId); 

我的頁面開始與一個或多個相冊是最初加載。

它應該首先得到相冊列表。

然後它加載所有專輯的元數據。

然後它加載每張專輯中的圖片。

然後它加載每張圖片的元數據。

我無法從單個服務器端調用加載它,因爲它很昂貴,所以我必須動態加載它。

是否有一個簡單的,骨幹的具體方式加載所有這些動態?目前,我正在讀取每個函數的fetch()返回的JSON,然後根據每次調用返回的結果進行下一個函數調用。

必須有一個更優雅的方式來做到這一點。

+1

最初你有專輯ID,對嗎?圖片id來自哪裏? –

+0

是的。相冊對象有一個列表這是該相冊中所有圖片的ID。 – ashwnacharya

回答

1

這裏是我的可能解決方案,我是依靠initialize方法。 最好從底部讀取代碼,由於定義順序被顛倒。對不起,沒有測試過代碼。

// Model for one picture 
var Picture = Backbone.Model.extend({ 
    // use urlRoot 
    // if after "pictures" fetch picture has an 'id' property, 
    // it will be appended to urlRoot on "picture" fetch 
    urlRoot: '/picture/metadata', 
    initialize: function() { 
     // get metadata for current picture 
     this.fetch(); 
    } 
}); 

// Model for Collection of Pictures 
var Pictures = Backbone.Collection.extend({ 
    model: Picture, 
    initialize: function(models, options) { 
     // get passed album id 
     this.album_id = options.album_id; 
     // automatically fetch pictures when collection is created from album model 
     // When items are fetched, Picture models are automatically created 
     // and their 'initialize' method is called 
     this.fetch(); 
    }, 
    // url property may be a function too 
    url: function() { 
     return '/pictures/' + this.album_id; 
    } 
}); 

// Model for album 
var Album = Backbone.Model.extend({ 
    // use urlRoot 
    // if after "albums" fetch album has an 'id' property, 
    // it will be appended to urlRoot on "album" fetch 
    urlRoot: '/album/metadata', 
    initialize: function() { 
     // get metadata for current album 
     this.fetch(); 

     // initialize pictures collection for current album 
     // pass album id 
     var pictures = new Pictures([], { album_id: this.get('id') }); 
     this.set('pictures', pictures); 
    } 
}); 

//Model for a collection of Albums 
var Albums = Backbone.Collection.extend({ 
    url: '/albums' 
    model: Album 
}); 

// Create albums collection 
var albums = new Albums(); 

// Get specific albums by ids 
// When items are fetched, Album models are automatically created 
// and their 'initialize' method is called 
albums.fetch({ 
    data : { 
     ids: [1,2,3,4,5] 
    } 
}); 
+0

這太棒了。謝謝! – ashwnacharya