如何将复选框值绑定到对象上的Knockout observableArray?

时间:2015-01-20 16:21:53

标签: knockout.js ko.observablearray

我有这样的事情:

var ScheduleDay = function(day, times) {
    var self = this;
    self.day = ko.observable(day || "");
    self.times = ko.observableArray(times || []);
};

function viewModel() {
    var self = this;
    self.schedule = ko.observableArray([
        new ScheduleDay("Monday"),
        new ScheduleDay("Tuesday"),
        new ScheduleDay("Wednesday"),
        new ScheduleDay("Thursday"),
        new ScheduleDay("Friday"),
        new ScheduleDay("Saturday"),
        new ScheduleDay("Sunday")
    ])
}

ko.applyBindings(new viewModel());

<input id="mondaySchedule" type="checkbox" data-bind="checked ???">

我每周的每一天都有3个复选框:早上,下午和晚上。我想要一个类似的模型:时间表:{星期一:[&#34;早上&#34;,&#34;下午&#34;],星期二:[&#34;下午&#34;]等。 }

1 个答案:

答案 0 :(得分:4)

正如您在评论中指定了您的问题,我建议您看看这个简单的标记,它会做您想做的事情:

<ul data-bind="foreach: schedule">
    <li>
        <strong data-bind="text: day"></strong>
        <input type="checkbox" data-bind="checked: times" value='morning' /> Morning
        <input type="checkbox" data-bind="checked: times" value='afternoon' /> Afternoon
        <input type="checkbox" data-bind="checked: times" value='evening' /> Evening
    </li>
</ul>

工作示例:http://jsfiddle.net/qjzbossb/