2012-09-11 3 views
0

다른 모델에 바인딩 된 컬렉션을 나열하는 뷰를 만들 수 있습니까? 또한 sort 함수를 사용할 수 있습니까?Backbone.js 뷰 내의 여러 모델

예를 들어 나는 '판매'및 '계정'모델을 보유하고 있으며 해당 부서에서 일하는 사람들의 모든 이름을 볼 수 있습니다.

감사합니다.

답변

3

확실히. 일반적으로 컬렉션에서 이벤트 리스너를 적용하여 각 모델을 나타내는 작은 하위 뷰를 만들고이를 통해 모델 이벤트 핸들러를 바인딩하는 방식으로 작업을 수행합니다.

BigView = Backbone.View.extend({ 
    el: 'ul', // This view is a <ul> and we'll be adding the model views 
    initialize: function() { 
     // This collection represents the collection you passed in 
     // For our purpose lets say it was a SalesCollection 
     this.collection.on('reset', this.addAllSales, this); 
     this.collection.on('add', this.addSale, this); 
    }, 
    addAllSales: function() { 
     var that = this; 
     this.collection.each(function(sale) { 
      that.addSale(sale); 
     }); 
    } 
    addSale: function(model) { 
     var view = new Subview({ 
      'model': model 
     }); 
     this.$el.append(view.render().el); 
    } 
}); 

SaleView = Backbone.View.extend({ 
    initialize: function() { 
     this.model.on('change', this.something, this); 
    }, 
    render: function() { 
     this.$el.html(); // Or whatever else you need to do to represent a sale as view 
     return this; 
    } 
    something: function(model) { 
     // Code for something 
    } 
}); 

이 예에서 기본적으로 판매 (예 : 판매)가있는 기본보기가 있습니다. 판매 컬렉션이 재설정되면 addAllSales()이 발생합니다. 판매가 컬렉션에 추가 될 때마다 특정 모델 (판매 모델)을 나타내는 하위 뷰가 추가됩니다. 이 하위 뷰에서는 바인딩 이벤트를 모델 변경 내용에 적용하여 처리합니다.

+0

감사합니다. 현재 가지고있는 코드는 주어진 코드와 비슷하지만 '판매'모델의 레코드를 같은 뷰에 어떻게 추가 할 수 있습니까? – CodePorter

+0

salesView가 나타내는 salesModel을 컬렉션이있는 bigView에 추가하는 방법은 무엇입니까? – jmk2142

+0

두 모델 모두 영업 및 계정에 "이름"필드가 있습니다. 이름을 보여주는 한 열과 부서를 보여주는 두 번째 열이있는 목록보기를 원합니다. 죄송합니다 질문이 명확하지 않은 경우. – CodePorter