I want to use ko.utils.arrayFilter()method in Knockout.js

Asked 1 years ago, Updated 1 years ago, 44 views

There is a list of strings, and there is a site that has the ability to type and search from the input box to query and filter the list.
I found an example of how it was made simple using knockout.js, but I would like to use ko.utils.arrayFilter() method to make it the same.

https://codepen.io/crkuplich/pen/VWgjXV

//Model
var locations = [
  { name: 'My House'},
  { name: 'Bakery',
  { name: 'Restaurant'},
  { name: 'Supermarket'},
  { name: 'Pub'}
];

// ViewModel
varViewModel=function(locations){
  varself = this;

  self.locations = locations;
  self.filter=ko.observable(');
  // filteredLocations is computed based on the filter observable
  // entered by the user
  This.filteredLocations=ko.computed(function(){
    return self.locations.filter(function(location){
      return location.name.indexOf(self.filter())!==-1;
    });
  });
}

ko.applyBindings (new ViewModel (locations)); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<!--The text field triggers the filtering with the textInput binding-->
<input type="text"placeholder="Filter locations" data-bind="textInput:filter">
<!--The lists through the computed observable-->
<ul data-bind="foreach:filteredLocations">
  <li data-bind="text:name"></li>
</ul>

javascript knockout.js

2022-09-30 13:52

1 Answers

ko.utils.arrayFilter specifies the array as the first argument.

//Model
var locations = [
  { name: 'My House'},
  { name: 'Bakery',
  { name: 'Restaurant'},
  { name: 'Supermarket'},
  { name: 'Pub'}
];

// ViewModel
varViewModel=function(locations){
  varself = this;

  self.locations = locations;
  self.filter=ko.observable(');
  // filteredLocations is computed based on the filter observable
  // entered by the user
  This.filteredLocations=ko.computed(function(){
    return ko.utils.arrayFilter(self.locations, function(location){
      return location.name.indexOf(self.filter())!==-1;
    });
  });
}

ko.applyBindings (new ViewModel (locations)); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<!--The text field triggers the filtering with the textInput binding-->
<input type="text"placeholder="Filter locations" data-bind="textInput:filter">
<!--The lists through the computed observable-->
<ul data-bind="foreach:filteredLocations">
  <li data-bind="text:name"></li>
</ul>


2022-09-30 13:52

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.