希望通过在用户点击提交按钮时更新KO数组来改善用户体验,而不是像Knockout那样自动完成。把这个测试页放在Fiddle上 - http://jsfiddle.net/HaSNd/ - 但是需要一个神奇的触摸......
JS:
function ViewModel() {
var self = this;
self.someVal = ko.observable();
self.items = ko.observableArray([{
someVal: "first item"
}]);
self.submitForm = function () {
self.items.push({
someVal: self.someVal()
});
};
self.updateItem = function () {
//Magic here
};
}
var vm = new ViewModel();
ko.applyBindings(vm);
HTML
<form data-bind="submit: submitForm">
<fieldset>
<p><b>Add items to array:</b>
</p>
<p>
<input data-bind="value: someVal" type="text" />
</p>
<p>
<button type="submit" data-bind="">Add item</button>
</p>
</fieldset>
</form>
<br />
<fieldset style="background-color: #eee; "> <b>Array summary:</b>
<br />
<ul data-bind="foreach: items">
<li data-bind="text: someVal"></li>
</ul>
</fieldset>
<p><b>Update items in array manually:</b>
</p>
<form data-bind="submit: updateItem, foreach: items">
<fieldset>
<p>
<input data-bind="value: someVal" />
</p>
<button type="submit" data-bind="">Update item</button> <button type="submit" data-bind="">Cancel</button>
</fieldset>
<br />
</form>
<br />
<br />
<span data-bind="text: ko.toJSON($root)"></span>