2014-02-05 2 views
0

에 중첩 된 모델과 컬렉션을로드 처음로드되었습니다.동적으로 나는 다음과 같습니다 백본 응용 프로그램이 백본

먼저 앨범 목록을 받아야합니다.

그런 다음 모든 앨범의 메타 데이터를로드합니다.

그러면 각 앨범에 그림이로드됩니다.

그런 다음 각 그림의 메타 데이터를로드합니다.

비싸기 때문에 단일 서버 측 호출에서 모든 것을로드 할 수 없으므로 동적으로로드해야합니다.

이 모든 것을 동적으로로드하는 간단한 백본 전용 방법이 있습니까? 현재, 각 함수의 fetch()에서 반환 된 JSON을 읽고 각 호출에서 반환 된 결과를 기반으로 다음 함수 호출을 작성합니다.

더 세련된 방법이 있어야합니다.

+1

처음에는 앨범 ID가 있습니까? 그림 ID는 어디서 오는 것입니까? –

+0

예. 앨범 객체에는 해당 앨범에있는 모든 그림의 ID 인 List 이 있습니다. – 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

관련 문제