Reputation: 11568
I have added the following filter to my view model:
contactsViewModel.filterItems = ko.computed(function () {
var filter = this.filterInput().toLowerCase();
if (!filter || !this.hasEnoughChars()) {
// Simply keep the results if input is empty or less 3 chars are in it
return this.contacts();
} else {
// iterate through the JSON again
return ko.utils.arrayFilter(this.contacts(), function (item) {
// Return the objects that contain the filter term
// ko.utils.stringContains is not part of knockout
// Manually added to knockout-2.2.0.debug.js line 238
return ko.utils.stringContains(item.firstName().toLowerCase(), filter)
|| ko.utils.stringContains(item.lastName().toLowerCase(), filter)
|| ko.utils.stringContains(item.email().toLowerCase(), filter)
|| ko.utils.stringContains(item.company().toLowerCase(), filter);
});
}
}, contactsViewModel);
How can I improve this code by reducing the number of times I call stringContains? I would like to be able to write:
return ko.utils.stringContains(item.FirstName().toLowerCase() || item.lastName().toLowerCase() || item.email().toLowerCase() || item.company().toLowerCase(), filter);
But stringContains doesn't return the right value when i do this
From knockout:
stringContains: function (string, contains) {
string = string || "";
return string.indexOf(contains) != -1;
}
Your help is much appreciated
Upvotes: 2
Views: 2731
Reputation: 3529
Using ko.utils.arrayFilter:
return ko.utils.arrayFilter([item.FirstName().toLowerCase(), item.lastName().toLowerCase(), item.email().toLowerCase(), item.company().toLowerCase()], function (str) { return str.indexOf(filter) != -1 }).length > 0;
Upvotes: 5