2013-04-12 1 views
17

모델 중 하나에서 컬렉션에 대한 참조를 얻는 방법이 있는지 궁금합니다. 예를 들어, 아래 컬렉션에있는 사람들 중 어떤 사람이 컬렉션에 속하거나 여러 컬렉션에 속해 있다는 것을 알고있는 경우입니다. Fiddle백본 - 모델에서 컬렉션을 가져올 수 있습니다.

(function() { 
window.App = { 
    Models: {}, 
    Views: {}, 
    Collections: {} 
}; 

App.Models.Person = Backbone.Model.extend({ 
    defaults: { 
     name: 'John', 
     phone: '555-555-5555' 
    } 
}); 

App.Views.Person = Backbone.View.extend({ 
    tagName: 'li', 

    template: _.template("<%= name %> -- <%= phone %>"), 

    render: function(){ 
     var template = this.template(this.model.toJSON()); 

     this.$el.html(template); 

     return this; 
    } 
}); 

App.Collections.People = Backbone.Collection.extend({ 
    model: App.Models.Person 
}); 

App.Views.People = Backbone.View.extend({ 
    tagName: 'ul', 

    add: function(person){ 
     var personView = new App.Views.Person({ model: person }); 

     this.$el.append(personView.render().el); 

     return this; 
    }, 

    render: function() { 
     this.collection.each(this.add, this); 

     return this; 
    } 
}); 


})(); 

var peeps = [ { name: 'Mary' }, { name: 'David' }, { name: 'Tiffany' } ]; 

var people = new App.Collections.People(peeps); 

var peopleView = new App.Views.People({ collection: people }); 

peopleView.render().$el.appendTo('body'); 

답변

25

각 모델은 collection라는 속성이 있습니다. 귀하의 바이올린에 console.log(people.models[0].collection)을 추가하면 컬렉션이 인쇄됩니다.

소스 코드를 살펴보면 모델의 destroy() 메서드가 호출 될 때 컬렉션에서 모델을 제거하는 등의 작업을 수행하는 것처럼 보입니다.

업데이트 : 3 인칭 모델과 2 개의 컬렉션을 만드는 this updated fiddle을 참조하십시오. 콘솔에 인쇄합니다. model.collection은 사람이 추가 된 첫 번째 컬렉션을 나타내며 두 ​​번째 컬렉션을 나타내지는 않습니다.

관련 문제