我有一个搜索表单:
<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>
我的ViewModel中的findBook
方法:
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'));
});
});
};
}
我错过了什么?
答案 0 :(得分:0)
您的findBook
函数正在尝试将books
计算的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());
};