Knockout - Filtering Objects In Observable Arrays By Multiple Object Properties
So here it is... I am attempting to build a data-grid with Knockout.js. I want to build it from scratch (skill building exercise), so I don't want to use KoGrid or SimpleGrid. The
Solution 1:
Just few problems in your code :
- a Boolean needs to be returned as output of ko.utils.arrayFilter
- you need a sort of sum up for arrayForEach as your filter is an OR
I changed your code to address those details :
var Filtering = function (data, columns) {
var self = this;
self.items = ko.observableArray(data);
self.columns = ko.observableArray(columns);
self.filter = ko.observable();
self.filteredItems = ko.computed(function () {
var filter = self.filter();
console.log(filter);
if (!filter) {
return self.items();
} else {
return ko.utils.arrayFilter(self.items(), function (item) {
console.log('Filtering on Item');
var matching = -1;
ko.utils.arrayForEach(self.columns(), function (c) {
var val = item[c.value];
if (typeof val === 'number') {
val = val.toString();
}
console.log('Filtering on Column');
matching+= val.toLowerCase().indexOf(filter.toLowerCase())+1;
});
console.log(matching);
return matching>=0;
});
}
});
};
Worked for me there : http://jsfiddle.net/Lzud7fjr/1/
Solution 2:
Your filtering case isn't returning anything. ko.utils.arrayFilter()
should return a truthy value if the item should be included in the result. However since it doesn't return anything, nothing is included in the result. You'll need to rewrite it so it will return something.
I suppose you could change the inner ko.utils.arrayForEach()
call to a filter and return true if the result is non-empty.
self.filteredItems = ko.computed(function () {
var filter = self.filter();
console.log(filter);
if (!filter) {
return self.items();
} else {
return ko.utils.arrayFilter(self.items(), function (item) {
console.log('Filtering on Item');
var result = ko.utils.arrayFilter(self.columns(), function (c) {
var val = item[c.value];
if (typeof val === 'number') {
val = val.toString();
}
console.log('Filtering on Column');
return val.toLowerCase().indexOf(filter.toLowerCase()) > -1;
});
return !!result.length;
});
}
});
Post a Comment for "Knockout - Filtering Objects In Observable Arrays By Multiple Object Properties"