0

我在尝试将数据映射到嵌套的 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>
4

1 回答 1

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库函数“地图”来创建视图模型数组。

此外,您的布局有错误。使用 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>
于 2013-11-07T04:36:51.633 回答