2012-10-10 2 views
0

필자는 "패싯 (faceting)"또는 "필터링"인터페이스 (데이터 작성 없음)를 구현하는 간단한 응용 프로그램을 작성합니다. 사용자가 왼쪽의 패싯 (확인란)을 선택하여 오른쪽의 결과 집합을 줄이기를 바랍니다.Backbone.js는 뷰 이벤트를 다른 뷰와 연결하는 데 도움이 필요합니다.

나는 2 개의 별도 컬렉션 (패싯과 인센티브)을 가지고 있습니다. 두 개의 항목으로 구성된 배열을 포함하는 단일 json 객체에서 채워집니다. 각각의 2 개 항목은 페이지의이 두 부분에 대한 모델,보기 및 모음을 만드는 데 도움이됩니다.

인센티브 수집 결과를 업데이트하려면 패싯보기에서 이벤트를 가져와야합니다. 이 두 가지를 연결하는 가장 좋은 방법은 무엇입니까? 내 테스트 응용 프로그램은 여기에서 찾을 수 있습니다. 템플릿 처리를 위해 Handlebars를 사용하고 있습니다.

는 여기를 참조하십시오 DEMO SITE

메인 콘텐츠 영역은 다음과 같습니다 : "자동차 인센티브"로 구성되어 있습니다.

//define Incentive model 
var Incentive = Backbone.Model.extend({ 
    defaults: { 
     photo: "car.png" 
    } 
}); 

//define individual incentive view 
var IncentiveView = Backbone.View.extend({ 
    tagName: "article", 
    className: "incentive-container", 
    template: Handlebars.compile($("#incentive-template").html()), 

    initialize: function() { 
     this.$el.html(this.template(this.model.toJSON())); 
     return this; 
    } 

}); 

//define Incentives collection 
var Incentives = Backbone.Collection.extend({ 
    model: Incentive, 
    url: 'data/incentives3.json', 
    parse: function(response) { 
     return response.incentiveHolder; 
    } 
}); 

var IncentivesView = Backbone.View.extend({ 
    el: $(".incentives-container"), 

    initialize: function() { 
     this.collection = new Incentives(); 


     // When the contents of the collection are set, render the view. 
     this.collection.on('reset', function() { 
      incentives = this.collection.models; 
      this.render(); 
     }, this); 

     this.collection.fetch(); 
     this.collection.on("reset", this.render, this); 
    }, 

    render: function() { 
     this.$el.find("article") 
      .remove(); 

     _.each(this.collection.models, function(item) { 
      this.renderIncentive(item); 
     }, this); 
    }, 

    renderIncentive: function(item) { 
     var incentiveView = new IncentiveView({ 
      model: item 
     }); 
     this.$el.append(incentiveView.render() 
      .el); 
    } 

}); 

는 패싯 모델/수집은 아래에 자세히 설명되어있다. FacetView에서 볼 수 있습니다 - 사용자가 체크 상자를 선택하면 "change"이벤트가 등록되었습니다. 이 데이터를 사용하여이 패싯 값을 포함하지 않는 각 인센티브를 숨기거나 2) FacetCollection (??)에서 모델을 제거하는 방법이 필요합니다. 사용자가 신속하게이 체크 박스를 켜고 끌 수 있기를 원합니다 - 느리게 (또는 덜 효율적으로) 제거/추가 한 다음 CSS로 숨기거나 표시하고 있습니까?

또한 내 displayIncentives() 함수에서 "this"가 뷰의 인스턴스임을 알 수 있습니다. 그러나 방금 클릭 한 체크 상자의 "값"에 액세스하려면 어떻게해야합니까?

이 값을 얻을 수 있다면 - 인센티브 컬렉션을 검토하고 각 항목을 반복 할 수 있으며 "인센티브"배열에 방금 클릭 한 확인란의이 값을 포함하는지 묻습니다. false를 반환하면 항목을 숨기거나 제거하고 계속 진행합니다.

// ====================================== 
// FACETS 
// ====================================== 

//define Facet model 
var Facet = Backbone.Model.extend({}); 

//define individual facet view 
var FacetView = Backbone.View.extend({ 
    tagName: "div", 
    className: "facet-group", 
    template: Handlebars.compile($("#facets-template").html()), 

    initialize: function() { 
     this.$el.html(this.template(this.model.toJSON())); 
     return this; 
    }, 

    events: { 
     "change input[type=checkbox]": "displayIncentives" 
    }, 

    displayIncentives: function() { 
     console.log(this); 
    } 

}); 

//define Facets collection 
var Facets = Backbone.Collection.extend({ 
    model: Facet, 
    url: 'data/incentives3.json', 
    parse: function(response) { 
     return response.facetsHolder; 
    } 
}); 

var FacetsView = Backbone.View.extend({ 
    el: $(".facets-container"), 

    initialize: function() { 
     this.collection = new Facets(); 

     // When the contents of the collection are set, render the view. 
     this.collection.on('reset', function() { 
      this.render(); 
     }, this); 

     this.collection.fetch(); 
    }, 

    render: function() { 
     _.each(this.collection.models, function(item) { 
      this.renderFacet(item); 
     }, this); 
    }, 

    renderFacet: function(item) { 
     var facetView = new FacetView({ 
      model: item 
     }); 
     this.$el.append(facetView.render().el); 
    } 

}); 

가 마지막으로 - 나의 JSON 개체가 여기에 있습니다 ... 나는이 객체가이 프로젝트의 다음 단계의 구조를 어떻게 설계하는 데 도움이 순간에 자유가있다. 어떤 제안이라도 대단히 감사합니다.

json object

+0

괜찮아요 - 이벤트 currentTarget.value에 액세스하여 확인란 값을 얻을 수 있다는 것을 알고 있습니다. 가까이와. – rsturim

+0

내 대답이 맞고 귀하의 질문에 대한 답변이 있습니까? - –

답변

1

무엇이 질문입니까? 실제로 많은 질문!

난 당신에게 내가 정확히 같은 작업을 수행하는 데 사용하고 논리를 이야기하고, 실제로 작동하는 (here 참조) 할 수

당신은 기본적으로이 컬렉션이 있어야합니다 측면의 수집 및 항목의 컬렉션을 .

면 집합 처음에는 비어 있습니다 (패싯이 선택되지 않음). 하나를 선택하면 패싯 컬렉션에 추가됩니다. 패싯을 추가 할 때 어떤 방법으로 항목 컬렉션을 필터링합니다 (항목 컬렉션으로 이벤트 청취를 트리거 할 수 있습니다.) - itemCollection.facet_filter()과 같은 메서드를 호출하면 facet_filter()이 항목 컬렉션 개체에서 정의한 메서드입니다. .

좋은.

상품 설명 일반 컬렉션입니다.목록을 필터링하고 재설정 이벤트를 트리거하는 facet_filter() 메소드를 추가하기 만하면됩니다. 이 재설정 이벤트는 목록을 다시 렌더링하는 FacetsView에 의해 수신됩니다.

facet_filter() 메소드는 이와 같아야합니다.

filter_results: function(facets){ 
    var filteredColletion= new Backbone.Collection(this.models); 
    _.each(facets,function(facet){ 
     filteredColletion.where({facet.key: facet.value}); 
      }); 
    this.reset(returnList); 
     } 
} 

이것은 내가 사용하는 논리이며 작동합니다.

관련 문제