2013-04-12 76 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()方法时从集合中删除模型。

更新:见this updated fiddle它创建三个人模型和两个集合。它将它们打印到控制台。它看起来像model.collection只是指人加入的第一个集合,而不是第二个集合。