绑定选择框中的选定项目不粘

时间:2012-11-06 17:00:50

标签: knockout.js

我有一个嵌套的集合......对象集合(LearningPath),每个集合中都有一个集合(LearningItems)。在UI中,我为所有LearningPaths绑定了一个表,然后为每个LearningPath的LearningIUtems绑定了一个SELECT框。当我选择一个项目时,所选项目总是返回到标题项目。这几乎就像是没有设置我所选项目的值。

以下是对象和视图模型的外观:

// namespace
var CPT = CPT || {};

// entities
CPT.LearningItem = function (liId, liTitle, liDescription, liType, liUrl) {
  this.id = liId;
  this.title = liTitle;
  this.description = liDescription;
  this.itemType = liType;
  this.url = liUrl;
};

CPT.LearningPath = function (lpId, lpTitle, lpDescription, lpPublishDate, lpPublishedBy) {
  this.id = lpId;
  this.title = lpTitle;
  this.description = lpDescription;
  this.pubDate = lpPublishDate;
  this.pubBy = lpPublishedBy;
  this.status = "";
  this.learingItems = ko.observableArray();

  if (this.pubDate !== null)
    this.status = "Published";
  else
    this.status = "Unpublished";
};

// view model
CPT.ViewModel = function () {
  this.selectedLearningItem = ko.observable();
  this.learningPaths = ko.observableArray();
};

这是绑定:

var learningPathsViewModel;

// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
  // setup view model
  learningPathsViewModel = CPT.ViewModel.Init();
});

这是选择框......

<table>
  <thead>
    <tr>
      <th>ID</th>
      <th>Title</th>
      <th>Status</th>
      <th>Learning Items</th>
    </tr>
  </thead>
  <tbody data-bind="foreach: learningPaths">
    <tr>
      <td data-bind="text: id"></td>
      <td data-bind="text: title"></td>
      <td data-bind="text: status"></td>
      <td>
        <select data-bind="optionsCaption: 'Select to view details...',
                            options: learingItems,
                            optionsText: 'title', 
                            value: learningPathsViewModel.selectedLearningItem">
        </select>
      </td>
    </tr>
  </tbody>
</table>
  <div class="displayBox"
    data-bind="with: selectedLearningItem">
  <h2>Learning Paths</h2>
    Selected item: (id:<span data-bind="text: id" />) <span data-bind="text: title" />
  </div>

1 个答案:

答案 0 :(得分:1)

selectedLearningItem属性应该在CPT.LearningPath对象内。因为在您的实现中,存储用于存储每行中的选定值的相同属性。

这是工作小提琴:http://jsfiddle.net/vyshniakov/w72bn/