Reputation: 25
Trying to filter a computed with multiple conditions. I have seen lots of examples where the return statement is nested with multiple conditions, but I truly dont understand why they work. My example here might not be a candidate for a nested return statements but I'm not sure how to execute this.
//ko.utils.arrayFilter - filter the items using the filter text
viewModel.filteredItems = ko.computed(function() {
var filter = this.filter().toLowerCase();
if (!filter) {
return this.items();
} else {
return ko.utils.arrayFilter(this.items(), function(item) {
return (item.fullName().toLowerCase().indexOf(filter) > -1);
});
}
//*** THIS LOGIC WORKS BY ITSELF BUT NOT COMBINED WITH THE ABOVE LOGIC ***
//var t = this.selectedTag();
//if (t == "all") return this.items();
//return ko.utils.arrayFilter(this.items(), function(item) {
// return item.tag == t;
//});
}, viewModel);
Here is the full example in fiddle: http://jsfiddle.net/boyus/qTb5Q/12/
Thanks in advance.
Upvotes: 1
Views: 2544
Reputation: 13278
I think the logic in your computed was slightly incorrect and you were not setting the selected tags correctly in the data-bind's.
Take a look at http://jsfiddle.net/qTb5Q/14/ for a working solution.
Here is the altered computed function:
viewModel.filteredItems = ko.computed(function() {
var filter = this.filter().toLowerCase();
if (!filter) {
var t = this.selectedTag().toLowerCase();
if (!t || t == "all") return this.items();
return ko.utils.arrayFilter(this.items(), function(item) {
return item.tag().toLowerCase() == t;
});
} else {
return ko.utils.arrayFilter(this.items(), function(item) {
return (item.fullName().toLowerCase().indexOf(filter) > -1);
});
}
}, viewModel);
Upvotes: 1