代码中存在许多 javascript 错误。
我已经分叉了 jsFiddle。由于视图中存在其他元素,而视图模型中不存在这些元素,因此会出现相同的错误。我故意这样离开它,这样你就可以从你停止的地方继续。关于如何实现它的基本思想是存在的。
jsFiddle 存在http://jsfiddle.net/rupesh_kokal/k7LHu/3/
下面是视图(或 html):
<table>
<tbody data-bind="template: {name: 'budgets', foreach: BudgetLine}">
</tbody>
</table>
<script id='budgets' type="text/html">
<tr>
<td>
<input type="text" data-bind="value:Title"></input>
</td>
<td>
<input type="text" data-bind="value:Amount"></input>
</td>
<td>
<span data-bind="text:Modified" />
</td>
<td>
<select data-bind="options:$root.Account,optionsCaption:'select Account', optionsText:'Title', OptionsValue:'Id', selectedOptions:Account().Id",size="5", multiple="true"></select>
</td>
<td>
<span data-bind="text:CostCenterId"></span>
</td>
<td>
<select data-bind="options:$root.Costcenter,optionsCaption:'cost center', optionsText:'Title', optionsValue:'Id', value:CostCenterId "></select>
</td>
<td>
<span data-bind="text:CostCenter().Company().Title"></span>
</td>
<td>
<input type="button" data-bind="click: $root.deleteItem" value="Delete" />
<input type="button" data-bind="click: $root.saveItem" value="save" />
</td>
</tr>
</script>
下面是视图模型:
function ModViewModel() {
var self = this;
self.Accounts = ko.observableArray([
{
Id: 1,
Title: "Account #1"},
{
Id: 2,
Title: "Account #2"},
{
Id: 3,
Title: "Account #3"},
{
Id: 2,
Title: "Account #1"}
]);
self.BudgetLine = ko.observableArray([]);
self.BudgetLine.push(new BudgetLineItem(1, "Budget #1", [1, 2], self));
self.BudgetLine.push(new BudgetLineItem(2, "Budget #2", [1, 2], self));
}
function BudgetLineItem(id, title, accountIds, parentModel) {
var self = this;
self.Id = id;
self.Title = title;
self.Account = ko.observableArray([]);
if (accountIds.length > 0) {
for (var i = 0, len = accountIds.length; i < len; i++) {
self.Account.push(new AccountLineItem(accountIds[i], parentModel));
}
}
else {
self.Account.push(new AccountLineItem(accountIds, parentModel));
}
}
function AccountLineItem(id, rootModel) {
var self = this;
self.Id = id;
self.Value = ko.computed(function() {
return rootModel.Accounts()[self.Id];
});
}
ko.applyBindings(new ModViewModel());