0

我有一个搜索表格:

<form class="navbar-search pull-right" data-bind="submit: findBook">
    <input type="text" class="search-query" placeholder="Search" id="search-input"> 
    <i class="icon-search"></i>
    <input type="submit" value="Submit">
</form>

我在这里列出这些书:

<ul id="container" class="list" data-bind="foreach: books">
    <li>
    <div>
    <table>
    <tr>
    <td class="center">
    <a data-bind="attr:{href: url}">            
       <img width="150" class="img-polaroid shadow" data-bind="attr:{src: image}">
    </a>
    </td>
    </tr>   
    <tr>
    <td class="center">
        <h6 data-bind="text: name"></h6>
    </td>
    </tr>
    </table>
    </div>
    </li>
</ul>

findBook我的 ViewModel 中有一个方法:

    self.books = ko.computed(function() {
        return ko.utils.arrayFilter(library, function(book) { 
          return self.selectedCategory() == null ||
              book.category === self.selectedCategory(); 
          })
    });
    self.findBook = function() {
        self.books = ko.computed(function() {
            return ko.utils.arrayFilter(library, function(book) {
                return book.name.match(new RegExp($('#search-input').val(), 'i'));   
            });
        });
    };       
}

我错过了什么?

4

1 回答 1

0

您的findBook函数正在尝试将books计算出的 observable 替换为不同的 observable。您的视图已经绑定到前一个视图,因此您不会在那里看到任何更改。

您需要更改books计算出的 observable 以依赖于某些过滤器。如果未设置过滤器,请包含该项目。如果设置了过滤器,请将其排除。

self.selectedCategory = ko.observable('');
self.nameFilter = ko.observable('');

self.books = ko.computed(function () {
    var selectedCategory = self.selectedCategory(),
        nameFilter = self.nameFilter(),
        selectedFilter = filter && new RegExp(filter, 'i');
    return ko.utils.arrayFilter(library, function (book) {
        var validCategory = !selectedCategory || book.category === selectedCategory,
            validFilter = !selectedFilter || book.name.match(selectedFilter);
        return validCategory && validFilter;
    });
});

self.searchInput = ko.observable();
self.findBook = function (element) {
    self.nameFilter(self.searchInput());
};

演示

于 2012-11-04T21:42:39.237 回答