我有一个这样的视图模型:
var Jobs = [
{ "Id": "J01", "Value": "description1" },
{ "Id": "J02", "Value": "description2" },
{ "Id": "J03", "Value": "description3" }
]
var Tasks = []
var Line = function (obj) {
var self = this;
self.Job = ko.observable(obj.JobId)
self.Task = ko.observable(obj.TaskId)
self.Job.subscribe(function () {
/*
Here i want to run ajax and fetch tasks for that
job and i assume this should work for related tasks dropdown only
*/
});
}
function ViewModel() {
var self = this
self.Timesheet = ko.observable()
self.LoadData = function () {
var data = {
"timesheet": {
"ApprovalStatus": 1,
"Description": "Timesheet",
"PeriodFrom": "2013-09-01",
"PeriodTo": "2013-09-15",
"RecId": "1",
"Lines": [{
"DestinationRecId": "D01",
"LaborCategoryRecId": "C01",
"PayTypeRecId": "PAY-01",
"ProjectRecId": "J01",
"ProjectWBSRecId": "J01-T01",
"RecId": "1"
}, {
"DestinationRecId": "D02",
"LaborCategoryRecId": "C01",
"PayTypeRecId": "PAY-02",
"ProjectRecId": "J02",
"ProjectWBSRecId": "J02-T01",
"RecId": "2"
}
}
}
self.Timesheet(data.timesheet)
for (var i = 0; i < data.timesheet.Lines.length; i++) {
var line = self.Timesheet().Lines[i]
var obj = {
JobId : line.ProjectRecId,
TaskId : line.ProjectWBSRecId
}
/* Here i am adding property SelectedItem and
* in it assigning a child object
*/
self.Timesheet().Lines[i].SelectedItem = new Line(obj)
console.log(self.Timesheet().Lines[i])
}
}
self.LoadData()
}
这是相应的视图:
<table>
<thead>
<tr>
<th>Job </th>
<th>Job WBS</th>
</tr>
</thead>
<tbody id="lines" data-bind="foreach:Timesheet().Lines">
<tr>
<td>
<select
data-bind="
options: Jobs,
optionsText: 'Value',
optionsValue: 'Id',
optionsCaption: 'Select Job',
value : $data.ProjectRecId
"
class="m-wrap">
<!-- $data.ProjectRecId $data.SelectedItem.Job-->
</select>
</td>
<td data-bind="with: Jobs">
<select
data-bind="
options: Tasks,
optionsText: 'Value',
optionsValue: 'Id',
value : $data.ProjectWBSRecId,
optionsCaption: 'Select Task'
"
class="m-wrap">
</select>
</td>
</tr>
</tbody>
</table>
问题是当我使用$data.SelectedItem.Job
它时说SelectedItem
没有定义。
使用$data.ProjectRecId
效果很好。目标是实现类似“ Knockout Dependent Dropdowns Handling ”之类的东西。
我想单独处理下拉菜单,但我失败了。
输出: