KnockoutJsを使用して検索リストを作成しています。コードは次のとおりです。
HTML:
<input type="search" id="search-bar" placeholder="Enter a name" data-bind="value:query,valueUpdate: 'keyup'">
<div id="list" data-bind='template: {foreach: name}'>
<li data-bind='text $data'></li>
</div>
Js検索機能の一部:
this.name = ko.observable('');
this.query = ko.observable('');
this.search = function (value) {
self.name([]);
for (var x in name) {
if (name[x].toLowerCase().indexOf(value.toLowerCase()) >= 0) {
self.name.push(name[x]);
}
}
}
this.query.subscribe(self.search);
データ(2-Dリスト)は$ .getを使用して別のURLから取得され、解析されます。次に、解析されたデータのすべての最初のエントリ(arsed_data [i] [0])を、コードに示されている監視可能な名前として割り当てました。
このリストは、検索ボックスのエントリに従ってコンテンツをフィルタリングすることを目的としており、最初はすべての名前が表示されますが、検索ボックスに何かを入力するとすぐに名前リストが空になります。考えられる原因は何ですか。修理する?
配列(実際にそうあるべきです)と現在の値のself.filteredNames
両方に依存する計算されたオブザーバブル(たとえば)を導入することをお勧めします。ビューモデル定義のフラグメントの代わりにテンプレートをバインドできます。次のようになります。self.names
ko.observableArray
self.query
self.filteredNames
self.names
self = this;
/* ... any other code related to VM */
self.names = ko.observableArray([]); // it's supposed to be later filled with AJAX requests
// self.names = ko.observableArray(['foo', 'bar', 'baz']); // however you can try with this not to bother with actual data loading
self.query = ko.observable('');
self.filteredNames = ko.pureComputed(function(){
// value of this pureComputed observable would be automatically updated each time either self.query or self.names is updated
return self.names().filter(function(item) {
return item.toLowerCase().indexOf(self.query().toLowerCase()) >= 0;
});
});
/* ... any other code related to VM */
それがどのように機能するかをテストできるマークアップのバージョンは、次のようになります。
<input type="search" id="search-bar" placeholder="Enter a name" data-bind="value:query,valueUpdate: 'keyup'">
<ul id = "list" data-bind='foreach: filteredNames'>
<li data-bind=' text: $data'></li>
</div>
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加