2013-04-12 28 views
17

Tôi tự hỏi liệu có cách nào để lấy một tham chiếu đến một bộ sưu tập từ một trong các mô hình của nó hay không. Ví dụ: nếu bất kỳ người nào trong bộ sưu tập bên dưới biết bằng cách nào đó thuộc về một bộ sưu tập hoặc nhiều bộ sưu tập. FiddleXương sống - Có thể lấy bộ sưu tập từ một mẫu

(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'); 

Trả lời

25

Mỗi mô hình có một tính chất gọi collection. Trong fiddle của bạn, thêm console.log(people.models[0].collection) sẽ in ra bộ sưu tập.

Nhìn qua mã nguồn, có vẻ như đây là những gì được sử dụng để thực hiện những việc như xóa mô hình khỏi bộ sưu tập khi phương thức destroy() của mô hình được gọi.

Cập nhật: xem this updated fiddle tạo mô hình ba người và hai bộ sưu tập. Nó in chúng vào giao diện điều khiển. Có vẻ như model.collection chỉ đề cập đến bộ sưu tập đầu tiên mà người đó đã được thêm vào, không phải là người thứ hai.

Các vấn đề liên quan