我在尝试在嵌套的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>
答案 0 :(得分:1)
试试这个:
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(123, data.TimeSlot);
self.participants.push(partViewModel);
};
};
我使用lodash库函数'map'来创建视图模型数组。
此外,您的布局有错误。使用timeSlots而不是viewModel.participants.timeSlots:
<tbody data-bind="foreach: participants">
<tr>
<td data-bind="text: Name"></td>
<td data-bind="text: roomName"></td>
<td data-bind="foreach: timeSlots">
<span data-bind="text: startTime"></span>
</td>
</tr>
</tbody>