【问题标题】:KnockoutJS filtering an arrayKnockoutJS 过滤数组
【发布时间】:2018-10-22 01:10:11
【问题描述】:

我有一个可观察数组,其中包含我要根据用户输入过滤的对象列表。如果用户搜索出现在数组中两个不同位置的单词,则过滤器函数应返回两个对象的标题,并删除或隐藏数组中与用户输入不匹配的所有其他对象。我必须使用淘汰赛 js 来执行此功能,这对我来说仍然是新的。目前,我的过滤器函数检查用户输入是否包含在数组中某个对象的标题中,如果不是,则删除该对象。但是,这并没有提供我需要的东西,因为它不能准确地过滤列表。

我的视图模式

var viewModel = function() {
var self = this;
self.filter = ko.observable('');
self.locationList = ko.observableArray(model);
self.filterList = function(){

    return ko.utils.arrayFilter(self.locationList(), function(location) {

      if(location.title == self.filter()){

        return location.title
      }

       else if( location.title.includes(self.filter()) ){

          return location.title
       }

       else{

          return self.locationList.remove(location)
       }

    });
  };
}

观点

   <section class="col-lg-2 sidenav">
      <div class="row">
        <div class="col-lg-12">
          <div class="input-group">
            <input data-bind="textInput: filter"
             type="text" class="form-control" placeholder="Filter Places"
             aria-describedby="basic-addon2" id="test">
            <button data-bind="click: filterList id="basic-addon2">
              <i class="glyphicon glyphicon-filter"></i>
            Filter
          </button>
          </div>
        </div>

        <div class="col-lg-12">
          <hr>
          <div data-bind="foreach: locationList">
            <p data-bind="text: $data.title"></p>
          </div>
        </div>
      </div>
    </section>

【问题讨论】:

  • @JasonSake 感谢您的回复,链接呈现错误请求
  • 过滤功能不应该这样使用。它应该只返回真/假。看看knockmeout.net/2011/04/utility-functions-in-knockoutjs.html

标签: javascript html knockout.js data-binding observable


【解决方案1】:

问题的答案可以在here Viraj Bhosale 的回答中找到

视图模型

var viewModel = function() {
var self = this;
self.filter = ko.observable('');
self.locationList = ko.observableArray(model);
self.filterList = ko.computed(function(){
    return self.locationList().filter(
      function(location){
        return (self.filter().length == 0 || location.title.toLowerCase().includes(self.filter().toLowerCase()));
      }
    );
  });
}

查看

<main class="container-fluid">
<div class="row">
    <section class="col-lg-2 sidenav">
      <div class="row">
        <div class="col-lg-12">
          <div class="input-group">
            <input data-bind="textInput: filter, valueUpdate: 'keyup'"
             type="text" class="form-control" placeholder="Filter Places"
             aria-describedby="basic-addon2" id="test">
          </div>
        </div>
        <div class="col-lg-12">
          <hr>
          <div data-bind="foreach: filterList">
            <p data-bind="text: $data.title"></p>
          </div>
        </div>
      </div>
    </section>
    <section class="col-lg-10" id="map"></section>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-30
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 2018-02-16
    • 1970-01-01
    相关资源
    最近更新 更多