2012-11-04 94 views
0

處理我有一個搜索表單:搜索形式Knockout.js

<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方法在我的視圖模型:

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

它應該通過名稱來過濾self.books數組,並在表單上編寫文本 – jviotti

+0

您是否可以刪除那些與您要求的問題無關的函數,幷包含HTML的(簡化)片段你綁定書籍元素? – BobS

回答

0

您的findBook函數正試圖用不同的值替代books計算的可觀察值。你的觀點已經被綁定到前一個,所以你不會在那裏看到任何改變。

您需要將您的books計算可觀察值更改爲取決於某個過濾器。如果過濾器未設置,請包含該項目。如果過濾器已設置,請將其排除。

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()); 
}; 

Demo