有一个下拉列表:
<div class="divInfoMargin">
There are
<select data-bind="options: numberOfChildren" class="mscSelect"></select>
</div>
我需要在上面显示以下选定的次数:
<div data-bind="foreach: children">
<div>
Name: <input data-bind="value: name" type="text" />
Date Of Birth <input type="text" data-bind="value: dob" class="datepicker" />
Residence :
<select data-bind="value: residence" name="residence" id="residence">
<option value="0">1</option>
<option value="1">2</option>
<option value="2">3</option>
</select>
</div>
</div>
Knockout viewmodel和一些粗略的想法:
function Child(name, dob) {
var self = this;
self.name = name;
self.dob = dob;
}
function AppViewModel() {
var self = this;
self.numberOfChildren = ko.observableArray(['1', '2', '3', '4', '5', '6']);
//this array needs to be added to:
self.children = ko.observableArray([]);
//self.addChild = function() {
// self.children.push(new Child(""));
//};
//This is not working code:
self.allChildren = ko.computed(function () {
var total = 0;
for (var i = 0; i < self.numberOfChildren().value; i++) {
self.children.push(new Child(""));
}
});
}
ko.applyBindings(new AppViewModel());
我对KO很新,很困惑。这是JSFiddle
答案 0 :(得分:1)
您的代码存在两个主要问题:
1)您的选择需要一个值绑定来保存所选值;你不能self.numberOfChildren().value
,你需要一个可观察的视图模型来保存该值。 (因此,您的数据绑定应该类似于<select data-bind="options: numberOfChildren, value: currentNumberOfChildren">
2)您应该只是让计算机返回您想要的数组,或者让一个可观察的数组具有填充它的预订,而不是尝试使用计算器来填充可观察数组。
Computed返回数组:
self.children = ko.computed(function () {
var children = [];
for (var i = 0; i < self.currentNumberOfChildren(); i++) {
children.push(new Child(""));
}
return children;
});
具有订阅的可观察数组:
self.children = ko.observableArray([]);
//Update self.children wehenver currentNumberOfChildren changes
self. currentNumberOfChildren.subscribe(function () {
var children = [];
for (var i = 0; i < self.currentNumberOfChildren(); i++) {
children.push(new Child(""));
}
self.children(children);
});
第一个更简单,但它不是一个可观察的数组,因此没有像self.children.push
那样的辅助方法(事实上,它是只读的),但是我亲自走了第一条路。
(工作JSFiddle)
答案 1 :(得分:1)
我稍微修改了你的代码,你需要在你的选择中设置一个选定的值,然后在你的计算中使用它,你有正确的想法。
<强> HTML 强>
<select data-bind="options: numberOfChildren, value: selectedNumberOfChildren" class="mscSelect"></select>
<强>的JavaScript 强>
self.selectedNumberOfChildren = ko.observable();
self.allChildren = ko.computed(function () {
var total = 0;
self.children.removeAll();
for (var i = 0; i < self.selectedNumberOfChildren(); i++) {
self.children.push(new Child(""));
}
});