I have this little ViewModel:
function BooksViewModel() {
var self = this;
self.books = ko.observableArray(library);
self.findByLanguage = function(lang) {
self.books = ko.computed(function() {
return ko.utils.arrayFilter(library, function(book) {
return book.language() === lang;
});
});
};
}
The findByLanguage method filters the array by language. In the view, im tryign to implement that like this:
<ul class="dropdown-menu">
<li><a tabindex="-1" href="#" data-bind="click: findByLanguage('C')">C</a></li>
<li><a tabindex="-1" href="#" data-bind="click: findByLanguage('Cpp')">C++</a></li>
</ul>
I’m attemping to reuse the function by calling the language parameter from there. But if I pass a function with parenthesis on data-bind it automatically gets called.
How can I accomplish this?
You might be interested in a slightly different approach that add extra fields into your View Model.
http://jsfiddle.net/jearles/RN9Dw/
By adding
languagesinto the View Model you can use Knockout to render the menu and theclickbinding will automatically pass the language that was clicked to the handler function. Additionally, addingselectedLanguageas an observable allows thebookscomputed to change when you select or clear a language.HTML
JS