i am trying to make a very simple search using knockout in a Durandal project. Demo in Jsfiddle
- What am i doing wrong here?
Is there a better way to implement search ?
var url = "https://www.googleapis.com/books/v1/volumes?q=the+Cat+In+The+Hat"; $.getJSON(url, function (data) { console.log(data.items); var books = data.items; var viewModel = { query: ko.observable('') }; viewModel.model = ko.mapping.fromJS(data.items); viewModel.books = ko.dependentObservable(function() { var search = this.query().toLowerCase(); return ko.utils.arrayFilter(books, function(book) { return book.kind.toLowerCase().indexOf(search) >= 0 || book.brewery.toLowerCase().indexOf(search) >= 0 || book.style.toLowerCase().indexOf(search) >= 0; }); }, viewModel); ko.applyBindings(viewModel); });
There are few mistakes in your code which is clearly visible to me:
I have created a fiddle to demonstrate a slightly better approach of searching according to your scenario.
Note: I used the latest stable version of knockout i.e. 3.0.0 and i recommend you to always use the latest version. You used dependentObservable in your code but Since Knockout 2.0, dependent observables are now called computed observables.
Fiddle (If fiddle not works than you should provide your api key in javascript code)
Main view model
Book object
Apply bindings
Note: Currently this code is not handling proper messages on error, on books not found, input query validation etc etc. You should handle it by yourself in order to provide better user experience.
Edit
I updated your code in fiddle check this its working.