If you want to ensure that your search results update only when triggered by a click event, rather than every time the query value changes, you can modify your approach slightly.
One way to achieve this is by creating a separate observable array called "results" and populating it with the search results upon clicking a button. Here's how you can implement this:
Start by defining the "results" array:
self.results = ko.observableArray([]);
Next, create a search function that updates the "results" array based on the query input:
self.search = function() {
if (!self.query()) {
self.results([]);
return;
}
self.results(ko.utils.arrayFilter(self.pageLinks(), function(item) {
return item.title.toLowerCase().indexOf(self.query().toLowerCase()) >= 0;
}) || []);
};
Once you have set up the "results" array and search function, adjust your binding to utilize the "results" array instead of a computed observable:
<tbody data-bind="foreach: results">
To complete the setup, remove the valueUpdate
setting from your <input>
element and include a button that triggers the search function:
<input placeholder="Search…" type="search" name="q" data-bind="value: query" autocomplete="off" />
<button type="button" data-bind="click: search">Go</button>
For a demonstration, you can check out this demo.