2013-08-22 1 views
1

방금 ​​Backbone.js로 시작했으며 중첩 모델 및 컬렉션에 문제가 있습니다.중첩 모델 및 컬렉션 (하위 컬렉션)을 만드는 방법

이 예에서는 단일 종단 점 /vocabulary.json 만 있습니다. 여기

는 반환 무슨의 샘플입니다

[ 
{ 
    "id": 1, 
    "words": [ 
     { 
      "native": "hello", 
      "foreign": "hola" 
     }, 
     { 
      "native": "yes", 
      "foreign": "si" 
     }, 
     { 
      //... More words in this lesson 
     } 
    ] 
}, 
{ 
    //... More lessons coming from this endpoint 
} 
] 

그것은 기본적으로 lessons의 모음으로, 그리고 각 lesson 어휘 words의 컬렉션이 있습니다.

다른 url 끝 점이없는 words 컬렉션을 만들려면 어떻게해야합니까 (컬렉션에 필요합니까?)?

여기까지 제가 지금까지 가지고 있습니다. 사실, 이것은 내가 노력하고있는 모든 것이 작동하지 않기 때문에 제거 된 기본 버전입니다.

내가이 완전히 잘못에 대해 생각하고, 아마

Entities.Vocabulary = Backbone.Model.extend({}); 

Entities.Vocabularies = Backbone.Collection.extend({ 
    model: Entities.Vocabulary, 
    url: "/vocabulary.json" 
}); 

// Here is where I am struggling 

Entities.Vocabulary.Word = Backbone.Model.extend({ 
    // what to do? 
}); 

Entities.Vocabulary.Words = Backbone.Collection.extend({ 
    // what to do? 
    // Need some method to go into the Entities.Vocabularies Collection, pluck a given id 
    // and return the "words" attribute as a new Collection to work from. 
}); 

을 /entities/vocabulary.js,하지만 난 당신이 나를 도와 도와 내 문제가 충분히 설명했다 희망하고있다.

답변

1

거의 다 왔어. 모델에 parse 메소드를 사용할 수 있습니다. 여기서 단어 컬렉션을 어휘 모델과 연관시키는 논리를 쓸 수 있습니다.이 라인의 어떤 것.

// This would be your main Model 
// Set the idAttribute on it 
// Use the parse method here which hits before initialize 
// where you attach the words collection on each Vocabulary Model 
Entities.Vocabulary = Backbone.Model.extend({ 
    idAttribute : 'id', 
    parse: function (response) { 
     // If theresponse has wods in response 
     // attach it words collection to the Vocabulary Model 
     if (response.words) { 
      this.words = new Entities.Vocabulary.Words(response.words || null, { 
       parse: true 
      }); 
     } 
     // Delete the words object from response as the collection is already 
     // created on the model 
     delete response.words; 

     return response; 
    } 
}); 

// Collection of Vocabulary 
Entities.Vocabularies = Backbone.Collection.extend({ 
    model: Entities.Vocabulary, 
    url: "/vocabulary.json" 
}); 

// This would be the model for Word inside a Specific Vocabulory 
// Associate a idAttribute if it has one. 
// Add a parse method if you have any other extra processing for this model 
Entities.Vocabulary.Word = Backbone.Model.extend({ 

}); 

// Just a Collection of words for the vocabulory 
Entities.Vocabulary.Words = Backbone.Collection.extend({ 

}); 


// Pass the object, and pass in the parse: true 
// parameter so that parse is called before initialize 
var vocabularies = new Entities.Vocabularies(navi, { 
    parse: true 
}); 

// If you want to fetch a new collection again you would just do 

//vocabularies.fetch({parse: true}); 


console.log(mainCollection); 

따라서 각 모델에는 어휘 모델에서 직접 단어 컬렉션이 있어야합니다.

Check Fiddle

관련 문제