1

저는 백본에 아직 완전히 익숙하지 않아서 제가하고있는 것에 중대한 오류가 있으면 미안합니다.백본 필터 수집 및 렌더링

내가 뭘 하려는지 아주 간단하게 보입니다. db 컬렉션에서 모델을 가져 와서 필터를 사용하십시오. 호텔을 필터링하려고한다고 가정 해 봅시다. 일단 주 컬렉션이 생기면 가격, 별, 기타 등등을 필터링하고 싶습니다. (물론 옐프 나 트립 어드바이저 등에서 찾을 수있는 것들입니다.) 그리고 물론 필터를 "리셋"하고 싶습니다. 사용자가 다른 확인란을 선택 취소합니다. - 하나의 뷰 결과가 표시됩니다 패널을 기반으로 - 하나 개의보기 모든 필터 - 각 항목 (각 호텔) 를 나타내는 템플릿을 기반으로 하나 개의보기 :

지금까지 나는 3 전망이 나는 사용하고 싶다.

내가 겪고있는 문제는 내가 내 필터를 되돌 리거나 새 컬렉션으로보기를 새로 고칠 수있는 상태에서 내 컬렉션을 유지할 수 있다는 것입니다. 제 문제가 어디 있는지 이해해 주시겠습니까? 그리고 어떻게해야합니까?

<script> 
// model 
var HotelModel = Backbone.Model.extend({}); 

// model view 
var ItemView = Backbone.View.extend({ 
    tagName : 'div', 
    className : 'col-sm-4 col-lg-4 col-md-4', 
    template : _.template($('#hotelItemTemplate').html()), 

    initialize : function() { 
     this.model.bind('change', this.render, this); 
     this.model.bind('remove', this.remove, this); 
    }, 

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

//view list 
var HotelListView = Backbone.View.extend({ 
    el : '#paginated-content', 

    events : { 
     "scroll" : "fetch" 
    }, 

    initialize : function(options) { 
     var items = this.collection; 
     items.on('add', this.add, this); 
     items.on('all', this.render, this);   
    }, 

    add : function(item) { 
     var view = new ItemView({ 
      model : item 
     }); 
     $('#paginated-content').append(view.render().el); 
    }, 

    fetch : function() { 
     this.collection.getNextPage(); 
    } 
}); 

// filterign menu 
var FilteringView = Backbone.View.extend({ 
    el : '#filtering', 

    // just examples of one of the filters that user can pick 
    events : { 
     'click #price_less_100 ' : 'updateValue', 
     'click #five_stars ' : 'updateStars', 
    }, 

    template : _.template($('#filteringTemplate').html()), 

    initialize : function() { 
     this.collection.on('reset', this.render, this); 
     this.collection.on('sync', this.render, this); 
    }, 

    render : function() { 
     this.$el.html(this.template); 
     return this; 
    }, 

    updateValue : function(e) { 

     //this is something I'm not using at the moment but that it contains a copy of the collection with the filters 
     var filtered = new FilteredCollection(coursesPaginated); 

     // if is checked 
     if (e.currentTarget.checked) { 
      var max = 100; 

      var filtered2 = _.filter(this.collection.models, function(item) { 
      return item.get("price") < max; 
      }); 

      //not used at the moment 
      //filtered.filterBy('price', function(item) { 
      // return item.get('price') < 100; 
      //}); 

      //this does not work 
      //this.collection.reset(filtered2); 

      //so I do this 
      this.collection.set(filtered2); 

     } else{ 
       // here, i would like to have something to put the collection in a state before this filter was applied   

      //something that I do not use at the moment 
      //filtered.removeFilter('price'); 
     } 

    }, 
    updateStars : function(e) { 
     //do something later 
    } 
}); 

// collection 
var HotelCollection = Backbone.PageableCollection.extend({ 
    model : HotelModel, 

    // Enable infinite paging 
    mode : "server", 

    url : '{{url("/api/hotels")}}', 

    // Initial pagination states 
    state : { 
     pageSize : 15, 
     sortKey : "updated", 
     order : 1 
    }, 

    // You can remap the query parameters from `state` keys from 
    // the default to those your server supports 
    queryParams : { 
     totalPages : null, 
     totalRecords : null, 
     sortKey : "sort" 
    }, 

    parse : function(response) { 
     $('#hotels-area').spin(false); 
     this.totalRecords = response.total; 
     this.totalPages = Math.ceil(response.total/this.perPage); 
     return response.data; 
    } 
}); 

$(function() { 
    hotelsPaginated = new HotelCollection(); 

    var c = new HotelListView({ 
     collection : hotelsPaginated 
    }); 


    $("#paginated-content").append(c.render().el); 
    hotelsPaginated.fetch(); 
}); 

이 사용 백본과 같이 필터링 할 그렇게 쉬운 일이 아닙니다 나에게 보인다. 누군가 다른 의견이 있으면 제발하십시오.

감사합니다. 이것에 대한

+0

컬렉션의 getNextPage()는 어디에 있습니까? – magmel

답변

0

내 솔루션 : 주기적으로 서버에서 가져

  1. 홈페이지 컬렉션.
  2. 필터링을 사용할 때마다 재설정되는 필터링 된 컬렉션.
  3. 필터링 된 컬렉션을 렌더링하는 데 사용되는 기본보기 (예 : 새 MainView ({collection : filteredCollection};)) 컬렉션 '재설정'이벤트에 대한 처리기가 이어야합니다.
  4. 필터 값을 포함하고 필터링 된 컬렉션을 새 값으로 재설정하도록 트리거하는 모델이있는 필터보기입니다.

Everithing easy. 코드 예제가 없으므로 유감스럽게 생각합니다.