2014-05-22 4 views
1

많은 양의 문서를 보유하고있는 Cars 컬렉션이 있습니다.체크 박스를 사용하여 컬렉션 필터링

각기 문서의 color 키에 해당하는 5 <input type="checkbox">이 있다고 가정 해 보겠습니다.

어떤 확인란을 선택했는지에 따라 선택기를 사용하여 컬렉션을 쿼리하려고합니다. 이 문제에 대한 최선의 해결책은 무엇입니까? 지금은 if 문장을 많이 쓰고있는 것처럼 보입니다. 더 좋은 방법이 있습니까?

감사

답변

1

당신은 세션 변수에 색상의 선택 (체크) 설정을 저장하고, 자동차를 반환하는 도우미에서 그 세션 변수의 값을 사용할 수 있습니다. 완전한 해결책은 아래와 같습니다. 이 두 파일을 새 프로젝트에 cars.htmlcars.js으로 저장하십시오.

<body> 
    {{> filter}} 
    {{> carList}} 
</body> 

<template name="filter"> 
    {{#each colors}} 
    <label> 
     <input type="checkbox" value="{{.}}" {{checked}} /> {{.}} 
    </label> 
    {{/each}} 
</template> 

<template name="carList"> 
    <ul> 
    {{#each cars}} 
     <li>{{make}} {{color}}</li> 
    {{/each}} 
    </ul> 
</template> 
if (Meteor.isClient) { 
    Cars = new Meteor.Collection(null); 

    Meteor.startup(function() { 
    Cars.remove({}); 
    Cars.insert({make: 'toyota', color: 'red'}); 
    Cars.insert({make: 'subaru', color: 'green'}); 
    Cars.insert({make: 'ford', color: 'brown'}); 
    Cars.insert({make: 'honda', color: 'white'}); 
    Cars.insert({make: 'datsun', color: 'yellow'}); 
    Cars.insert({make: 'doge', color: 'yellow'}); 
    }); 

    // return a unique list of colors from the Cars collection 
    Template.filter.colors = function() { 
    return _.uniq(Cars.find().map(function (car) { return car.color; })); 
    }; 

    Session.setDefault('colors', []); 

    // if any checkbox was clicked, map across all checked inputs, and 
    // store resulting array of colors in session variable 
    Template.filter.events({ 
    'click input[type=checkbox]': function (ev, tpl) { 
     var colors = tpl.$('input:checked').map(function() { 
     return $(this).val(); 
     }); 
     Session.set('colors', $.makeArray(colors)); 
    } 
    }); 

    // attribute helper for checked colors 
    Template.filter.checked = function() { 
    if (_.contains(Session.get('colors'), this.toString())) { 
     return {checked: true}; 
    } 
    }; 

    // return all cars with that have a color in the session variable 
    Template.carList.cars = function() { 
    return Cars.find({color: {$in: Session.get('colors')}}); 
    }; 

} 
+0

감사 라이언, 체크 박스의 매핑은 내가 필요 정확히이다. – Nathan

관련 문제