您可以使用ko.computed
和textInput
結合始終通知更改並應用過濾器。
請參閱snnipet。
function ViewModel(){
var self =this;
this.filter = ko.observable();
this.places = ko.observableArray([{name:"New York"},{name:"Los Angeles"},{name:"Curitiba"},{name:"Rio de Janeiro"}]);
this.visiblePlaces = ko.computed(function(){
return this.places().filter(function(place){
if(!self.filter() || place.name.toLowerCase().indexOf(self.filter().toLowerCase()) !== -1)
return place;
});
},this);
}
ko.applyBindings(new ViewModel());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<label for="filter">Filter:</label>
<input id="filter" type="text" data-bind="textInput: filter"/>
<ul data-bind="foreach: visiblePlaces">
<li data-bind="text: name"></li>
</ul>