在其他地方显示knockout viewmodel子元素

时间:2013-06-05 06:21:22

标签: knockout.js viewmodel

我定义了以下viewmodel:

function BookCartViewModel() {
this.Books = ko.observableArray([]);
this.Categories = ko.observableArray([]);
}

var Book = function (data) {
   this.ISBN = ko.observable(data.ISBN);
   this.BookID = ko.observable(data.BookID);
   this.BookName = ko.observable(data.Name);
   this.Price = ko.observable(data.Price);
   this.Publisher = ko.observable(data.Publisher);
   this.PublishedDate = ko.observable(data.PublishedDate);
   this.Authors = ko.observableArray(data.Authors);
   this.Category = ko.observable(data.Category);
   this.Reviews = ko.observableArray([]);
   var items = $.map(data.BookReviews, function (d) { return new Review(d) });

   this.ShowReviews = function () {
   }
 }

var Review = function (data) {
   this.ReviewID = ko.observable(data.ReviewID);
   this.Reviewer = ko.observable(data.ReviewerName);
   this.Email = ko.observable(data.Email);
   this.BookID = ko.observable(data.FkBookID);
   this.ReviewDate = ko.observable(data.ReviewDate);
   this.Comments = ko.observable(data.Comments);
   this.Rating = ko.observable(data.Rating);
}

我的观点如下,以表结构显示书籍:

 <tbody data-bind="foreach:Books">
    <tr>
        <td style="width:20%; text-align:left;" data-bind="text:ISBN"></td>
        <td style="width:20%; text-align:left;" data-bind="text:BookName"></td>
        <td style="width:30%; text-align:left;" data-bind="text:Authors"></td>
        <td style="width:10%; text-align:left;" data-bind="text:Price"></td>
        <td style="width:10%; text-align:left;" data-bind="text:PublishedDate"></td>
        <td style="width:10%; text-align:left;">
            <input id="btnShowReviews" type="button" value="Reviews"  data-      bind="click:ShowReviews" />
        </td>
    </tr>       
   </tbody>

现在我要做的是在SEPERATE表格中显示书籍的评论,点击评论按钮下方。我如何通过定义视图模型的方式来实现这一目标?还是需要改变?

请帮忙

2 个答案:

答案 0 :(得分:1)

  1. 制作一个Book类型的变量,该变量将存储在所选的或书中以供审核
  2. 如果要审阅的图书不为空,请创建一个可见的div,然后映射所需的属性
  3. 如果没有选择书籍进行审核,则隐藏该div

答案 1 :(得分:1)

function BookCartViewModel() {
    this.Books = ko.observableArray([]);
    this.Categories = ko.observableArray([]);
    this.SelectedBook = ko.observable();

    this.selectBook = function(book, event) {
        this.SelectedBook(book);
    }
}

<div id="bookReview" data-bind="if: SelectedBook">
  <table data-bind="foreach: SelectedBook.Reviews">
    <!-- ... -->
  </table>
</div>

现在您只需要一个通过SelectedBook写入data-bind="click: $root.selectBook"的按钮。