javascript 可观察数组中的敲除搜索

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29667134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:52:40  来源:igfitidea点击:

Knockout search in observable array

javascriptknockout.jsknockout-2.0

提问by cactodevcie

I try to search by name in observable array. Here's my code:

我尝试在可观察数组中按名称搜索。这是我的代码:

<input class="form-control" data-bind="value: Query, valueUpdate: 'keyup'" autocomplete="off">

And my code in ViewModel

我在 ViewModel 中的代码

viewModel.Query = ko.observable('');

viewModel.search =  function(value) {
    viewModel.TestList.removeAll();
    for (var x in viewModel.TestList) {
        if (viewModel.TestList[x].Name.toLowerCase().indexOf(value.toLowerCase()) >= 0) {
            viewModel.TestList.push(viewModel.TestList[x]);
        }
    }
}
viewModel.Query.subscribe(viewModel.search);

First: I would like to search by name string. Two: Is there any other sollutions to not remove all elements from the view? I mean when query string is empty, there should be all list again.

第一:我想按名称字符串搜索。二:是否有其他解决方案不从视图中删除所有元素?我的意思是当查询字符串为空时,应该再次列出所有列表。

Now I have error message:

现在我有错误消息:

TypeError: viewModel.TestList[x].Name is undefined

回答by Jeroen

Use a computed observable array to show search results, along these lines:

使用计算出的 observable 数组来显示搜索结果,如下所示:

var viewModel = {
  items: [ { Name: "Apple part" }, { Name: "Apple sauce" }, { Name: "Apple juice" }, { Name: "Pear juice" }, { Name: "Pear mush" }, { Name: "Something different" } ]
};

viewModel.Query = ko.observable('');

viewModel.searchResults = ko.computed(function() {
    var q = viewModel.Query();
    return viewModel.items.filter(function(i) {
      return i.Name.toLowerCase().indexOf(q) >= 0;
    });
});

ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<input class="form-control" data-bind="value: Query, valueUpdate: 'keyup'" autocomplete="off">

<h3>Search results:</h3>
<ul data-bind="foreach: searchResults">
  <li data-bind="text: Name"></li>
</ul>

<h3>All items:</h3>
<ul data-bind="foreach: items">
  <li data-bind="text: Name"></li>
</ul>

This also removes the need for a subscription or seperate function.

这也消除了对订阅或单独功能的需要。

This example utilizes:

这个例子利用了:

As you can see in the example, itemswill always contain all objects, and searchResultsis just a filtered read-only view on that array.

正如您在示例中看到的,items将始终包含所有对象,并且searchResults只是该数组上的过滤只读视图。