Knockout Filtering on Observable Array

前端 未结 3 1074
天命终不由人
天命终不由人 2020-12-30 18:51

I\'ve started learning Knockout and I\'m having some trouble filtering an observable array on a button click and displaying the results.

This is my model:

         


        
3条回答
  •  温柔的废话
    2020-12-30 19:26

    You cannot have a function with parameters inside a ko.computed.

    What you need is store the current filter in a new property and use that in your computed

    function ProductModel() {
        var self = this;
        self.products = ko.observableArray([]);
    
        self.currentFilter = ko.observable(); // property to store the filter
    
        //...
    
        self.filterProducts = ko.computed(function() {
            if(!self.currentFilter()) {
                return self.products(); 
            } else {
                return ko.utils.arrayFilter(self.products(), function(prod) {
                    return prod.genre == self.currentFilter();
                });
            }
        });
    }
    

    And in your click handler just set the current filter:

    
    
    self.filter = function(genre) {
        self.currentFilter(genre);
    }
    

    Demo JSFiddle

    Note the function() { } in needed if you want to pass additional arguments a in click binding (see also in the documentation), otherwise Knockout would execute your function when it parses the binding and not when you click on the button.

提交回复
热议问题