我在尝试将数据映射到嵌套的 observableArray (timeSlots) 时遇到了麻烦。当我填充我的参与者 observableArray 时,它工作得很好。我敢打赌,当它嵌套时,我必须做一些特别的事情。
我是Knockout的新手,所以不确定我做错了什么。我一直在查看文档无济于事,尤其是在:
http://knockoutjs.com/documentation/plugins-mapping.html
这是我的代码:(已编辑)
<script type="text/javascript">
var TimeSlot = function (startTime, endTime) {
var self = this;
self.startTime = startTime;
self.endTime = endTime;
};
var Participant = function (id, timeSlots) {
var self = this;
self.Name = id;
self.roomName = ko.observable();
self.timeSlots = ko.observableArray();
var timeSlotVMs = _.map(timeSlots, function(ts) {
return new TimeSlot(ts.startTime, ts.endTime);
});
ko.utils.arrayPushAll(self.timeSlots(), timeSlotVMs);
};
function ViewModel() {
var self = this;
self.participants = ko.observableArray([]);
self.addPerson = function () {
var data = '{"TimeSlot":[{"startTime":"05:23","endTime":"06:32"},
{"startTime":"10:23","endTime":"11:32"}]}';
var partViewModel = new Participant(self.selectedValue().Id(), data.TimeSlot);
self.participants.push();
};
};
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
</script>
如果需要,还有 HTML:
<tbody data-bind="foreach: viewModel.participants">
<tr>
<td data-bind="text: Name"></td>
<td data-bind="text: roomName"></td>
<td data-bind="foreach: viewModel.participants.timeSlots">
<span data-bind="text: startTime"></span>
</td>
</tr>
</tbody>