将过滤器应用于observableArray?

时间:2015-11-08 07:33:27

标签: javascript knockout.js

我正在开发一个项目,我有一个搜索字段,根据搜索框中输入的内容过滤observableArray。

这是我的HTML代码:

                <input class="form-control" placeholder="Search for a burger joint around downtown Indianapolis, IN" data-bind="value: searchInput, valueUpdate: 'afterkeydown', event: { keyup: filterResults }">

这是我的js代码:

var BurgerJoint = function(data) {
    this.id = ko.observable(data.id);
    this.name = ko.observable(data.name);
    this.long = ko.observable(data.long);
    this.lat = ko.observable(data.lat);
    this.comments = ko.observable(data.comments);
}

var ViewModel = function() {
    var self = this;
    self.searchInput = ko.observable('');

    this.burgerList = ko.observableArray([]);

    initialBurgerJoints.forEach(function(burgerItem){
        self.burgerList.push( new BurgerJoint(burgerItem) );        
        addmarker(burgerItem.lat, burgerItem.long, burgerItem.id, burgerItem.name, burgerItem.comments);
    });

    self.burgerList.sort(function (l, r) { return l.name() > r.name() ? 1 : -1 });

    self.currentFilter = ko.observable();

    self.filterResults = function(){
        var value = self.searchInput().toLowerCase();
        if(value != ''){
            self.burgerList(self.burgerList.filter(function(data){
                var startsWith = data.name.toLowerCase().startsWith(value);
                return burgerList;
            }));
        }
        return true;
    };

    self.showmap = function(data) {
        viewmarker(data.id());
    };      
}

    ko.applyBindings(new ViewModel());

我遇到过filterResults函数的问题。有什么建议吗?

1 个答案:

答案 0 :(得分:2)

也许您不应该在过滤功能中设置原始burgerList。首先复制/克隆原始文件。尝试像

这样的东西
    self.filterResults = function(){
        var value = self.searchInput().toLowerCase();
        if(value != ''){
            self.burgerList(self.burgerList().filter(function(data){
                return data.name.toLowerCase().startsWith(value);
            }));
        }else{
          // reset with the original burgerList contents here
          self.burgerList(self.burgerListClone());
        }
    };