Sample book list

by val2048

HTML

<script src="https://github.com/downloads/SteveSanderson/knockout/jquery.tmpl.js"></script>
<script src="http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-1.2.1.debug.js"></script>
<script src="https://raw.github.com/douglascrockford/JSON-js/master/json2.js"></script>
<h3> Books </h3>

<form>
    <div>
        <p>Search <input type="text" data-bind="value: bookSearchText"/>
            <input type="submit" data-bind="click: search" value="Search"/>
        </p>
        
    </div>
</form>
<h3 data-bind="visible: bookLoading()">Loading</h3>
<div data-bind="visible: foundBooks().length > 0">
    <h4>Found books</h4>
    <ul data-bind="template: { name: 'bookTemplate', foreach: foundBooks }"></ul>
</div>

<script type="text/html" id="bookTemplate">
    <li data-bind="click: select">
        ${$data.isSelected()}
        {{if $data.isSelected()}}
          Selected!
        {{/if}}
        <span data-bind="text: title"></span>
    </li> 
</script>

JavaScript

function sendAjaxSearch(searchString, callback, context) {
    new $.ajax('/echo/json/', {
        type: 'POST',
        data: {
            json: JSON.stringify({
                books: [
                    {
                    title: searchString + " 1"},
                {
                    title: searchString + " 2"}
                ]
            }),
            delay: 0
        },
        success: function(data) {
            callback.call(context, data);
        }
    });
}


function book(title, parentVm) {
    this.title = ko.observable(title);
    this.select = function()
        {
            parentVm.selected(this);
        }
    this.isSelected = ko.dependentObservable(function()
                                             {
        alert(parentVm.selected() == this);
                                                 return parentVm.selected() == this;
                                             });
}

function bookSearchViewModel() {
    this.bookSearchText = ko.observable();
    this.bookLoading = ko.observable(false);
    this.foundBooks = ko.observableArray([]);
    this.selected = ko.observable(null);
    this.search = function() {
        this.bookLoading(true);
        sendAjaxSearch(this.bookSearchText(), function(r) {
            this.foundBooks.removeAll();
            for (var i = 0; i < r.books.length; i++) {
                this.foundBooks.push(new book(r.books[i].title, this));
            }
            this.bookLoading(false);
        }, this);
    };
}
ko.applyBindings(new bookSearchViewModel());