Display Item Details
by Mike Wasson
In this section, you will add the ability to view details for each book. In app.js, add to the following code to the view model:
[!code-javascriptMain]
1: self.detail = ko.observable();
2:
3: self.getBookDetail = function (item) {
4: ajaxHelper(booksUri + item.Id, 'GET').done(function (data) {
5: self.detail(data);
6: });
7: }
In Views/Home/Index.cshtml, add a data-bind element to the Details link:
[!code-htmlMain]
1: <ul class="list-unstyled" data-bind="foreach: books">
2: <li>
3: <strong><span data-bind="text: AuthorName"></span></strong>: <span data-bind="text: Title"></span>
4: <!-- New code -->
5: <small><a href="#" data-bind="click: $parent.getBookDetail">Details</a></small>
6: </li>
7: </ul>
This binds the click handler for the <a> element to the getBookDetail
function on the view model.
In the same file, replace the following mark-up:
[!code-htmlMain]
1: <div class="col-md-4">
2: <!-- TODO: Book details -->
3: </div>
with this:
[!code-htmlMain]
1: <!-- ko if:detail() -->
2:
3: <div class="col-md-4">
4: <div class="panel panel-default">
5: <div class="panel-heading">
6: <h2 class="panel-title">Detail</h2>
7: </div>
8: <table class="table">
9: <tr><td>Author</td><td data-bind="text: detail().AuthorName"></td></tr>
10: <tr><td>Title</td><td data-bind="text: detail().Title"></td></tr>
11: <tr><td>Year</td><td data-bind="text: detail().Year"></td></tr>
12: <tr><td>Genre</td><td data-bind="text: detail().Genre"></td></tr>
13: <tr><td>Price</td><td data-bind="text: detail().Price"></td></tr>
14: </table>
15: </div>
16: </div>
17:
18: <!-- /ko -->
This markup creates a table that is data-bound to the properties of the detail
observable in the view model.
The ???<!??? ko ???>??? syntax lets you include a Knockout binding outside of a DOM element. In this case, the if
binding causes this section of markup to be displayed only when details
is non-null.
[!code-htmlMain]
1: <!-- ko if:detail() -->
Now if you run the app and click one of the ???Detail??? links, the app will display the book details.
|