

文字列のリストがあり、inputボックスからタイプして検索をかけると、リストと照会してフィルターされるという機能のサイトがあります。  
knockout.jsを使ってシンプルにできた例を見つけたのですが、これにko.utils.arrayFilter()
methodを使って同じ機能にしたいです。

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

[code]

    // Model
    var locations = [
      { name: 'My House' },
      { name: 'Bakery' },
      { name: 'Restaurant' },
      { name: 'Supermarket' },
      { name: 'Pub' }
    ];
    
    // ViewModel
    var ViewModel = function(locations) {
      var self = 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));
[/code]

[code]

    <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 list iterates through the computed observable -->
    <ul data-bind="foreach: filteredLocations">
      <li data-bind="text: name"></li>
    </ul>
[/code]


CC BY-SA 4.0
2018-08-17T05:04:16.273
47579
2018-08-17T09:18:40.583
2018-08-17T09:18:40.583
19759
22895
question
javascript knockout.js
knockout.jsでko.utils.arrayFilter() methodを使いたい


以下でいかがでしょうか。`ko.utils.arrayFilter` では第1引数に配列を指定します。

[code]

    // Model
    var locations = [
      { name: 'My House' },
      { name: 'Bakery' },
      { name: 'Restaurant' },
      { name: 'Supermarket' },
      { name: 'Pub' }
    ];
    
    // ViewModel
    var ViewModel = function(locations) {
      var self = 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));
[/code]

[code]

    <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 list iterates through the computed observable -->
    <ul data-bind="foreach: filteredLocations">
      <li data-bind="text: name"></li>
    </ul>
[/code]


CC BY-SA 4.0
2018-08-17T05:44:10.417
47581
2018-08-17T05:44:10.417
19759
47579
answer