显示项详细信息Display Item Details

作者: Mike Wassonby Mike Wasson

下载完成的项目Download Completed Project

在本部分中,你将添加查看每个书籍的详细信息的能力。In this section, you will add the ability to view details for each book. 在 node.js 中,将以下代码添加到视图模型:In app.js, add to the following code to the view model:

self.detail = ko.observable();

self.getBookDetail = function (item) {
    ajaxHelper(booksUri + item.Id, 'GET').done(function (data) {
        self.detail(data);
    });
}

在 Views/Home/索引中,将数据绑定元素添加到详细信息链接:In Views/Home/Index.cshtml, add a data-bind element to the Details link:

<ul class="list-unstyled" data-bind="foreach: books">
  <li>
    <strong><span data-bind="text: AuthorName"></span></strong>: <span data-bind="text: Title"></span>
    <!-- New code -->
    <small><a href="#" data-bind="click: $parent.getBookDetail">Details</a></small>
  </li>
</ul>

这会将 <> 元素的 click 处理程序绑定到视图模型上的 getBookDetail 函数。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:

<div class="col-md-4">
    <!-- TODO: Book details -->
</div>

替换为以下内容:with this:

<!-- ko if:detail() -->

<div class="col-md-4">
<div class="panel panel-default">
  <div class="panel-heading">
    <h2 class="panel-title">Detail</h2>
  </div>
  <table class="table">
    <tr><td>Author</td><td data-bind="text: detail().AuthorName"></td></tr>
    <tr><td>Title</td><td data-bind="text: detail().Title"></td></tr>
    <tr><td>Year</td><td data-bind="text: detail().Year"></td></tr>
    <tr><td>Genre</td><td data-bind="text: detail().Genre"></td></tr>
    <tr><td>Price</td><td data-bind="text: detail().Price"></td></tr>
  </table>
</div>
</div>

<!-- /ko -->

此标记创建一个表,该表绑定到视图模型中的 detail 的属性。This markup creates a table that is data-bound to the properties of the detail observable in the view model.

"<!--ko>" 语法允许在 DOM 元素之外包含挖空绑定。The "<!-- ko -->" syntax lets you include a Knockout binding outside of a DOM element. 在这种情况下,仅当 details 为非 null 时,if 绑定才会显示此部分标记。In this case, the if binding causes this section of markup to be displayed only when details is non-null.

<!-- ko if:detail() -->

现在,如果运行应用并单击 "详细信息" 链接之一,该应用将显示书籍详细信息。Now if you run the app and click one of the "Detail" links, the app will display the book details.