knockout js checkbox过滤器使用ko.utils.arrayFilter

时间:2013-11-21 18:22:12

标签: knockout.js

我采用了这个例子

http://knockoutjs.com/examples/animatedTransitions.html

并用复选框替换了无线电输入,如果我返回planet.type manualy但是我需要返回超过1行星的类型。 示例1 http://www.html5imageeditor.co.uk/kopush/filter.php 例2 http://www.html5imageeditor.co.uk/kopush/filter2.php

查看

       <label><input type='checkbox' name="type" data-bind='value: "all" ,checked: typeToShow' />All</label>
       <label><input type='checkbox' name="type" data-bind='value: "rock" ,checked: typeToShow' />Rock</label>
       <label><input type='checkbox' name="type" data-bind='value: "gasgiant" ,checked: typeToShow' />Gas Giant</label>
   <div data-bind='template: { foreach: planetsToShow,
                               beforeRemove: hidePlanetElement,
                               afterAdd: showPlanetElement }'>
       <div data-bind='attr: { "class": "planet " }'><span data-bind="text: name "></span></div>
   </div>

模型

var PlanetsModel = function() {
   this.planets = ko.observableArray([
        { name: "Mercury", type: "rock"},
        { name: "Venus", type: "rock"},
        { name: "Earth", type: "rock"},
        { name: "Mars", type: "rock"},
        { name: "Jupiter", type: "gasgiant"},
        { name: "Saturn", type: "gasgiant"},
        { name: "Uranus", type: "gasgiant"},
        { name: "Neptune", type: "gasgiant"},
        { name: "Pluto", type: "rock"}
    ]);

   this.typeToShow = ko.observableArray(["all"]);

   this.planetsToShow = ko.computed(function() {

       var desiredType = this.typeToShow();
       if (desiredType == "all") return this.planets();
       return ko.utils.arrayFilter(this.planets(), function(planet) {

        return planet.type == 'rock' || planet.type == 'gasgiant';//shows all how can i oproduce this result dynamicly ?
       //return planet.type == 'rock' shows just the rock
       });
   }, this);


   this.showPlanetElement = function(elem) { if (elem.nodeType === 1) $(elem).hide().slideDown() }
   this.hidePlanetElement = function(elem) { if (elem.nodeType === 1) $(elem).slideUp(function() { $(elem).remove(); }) }
};


ko.bindingHandlers.fadeVisible = {
   init: function(element, valueAccessor) {

       var value = valueAccessor();
       $(element).toggle(ko.utils.unwrapObservable(value));
   },
   update: function(element, valueAccessor) {

       var value = valueAccessor();
       ko.utils.unwrapObservable(value) ? $(element).fadeIn() : $(element).fadeOut();
   }
};

ko.applyBindings(new PlanetsModel());

你可以看到手动设置返回我需要像planet.type =='rock'||一样动态创建它planet.type =='gasgiant'希望它能成为一个

谢谢

1 个答案:

答案 0 :(得分:2)

我已经成功地在另一个jsfiddle的帮助下解决了这个问题,如果有帮助http://www.html5imageeditor.co.uk/kopush/filter-working.php