如果你把问题转过来,效果会更好。将验证添加到您尝试添加的可观察文本(或可观察对象,如果涉及多个字段)。然后当你触发添加时,检查 observable 是否有效。如果有效,则将其添加到数组中。
http://jsfiddle.net/jearles/XY9XH/
--
<span>New Item: <input data-bind="value:newItem" /> <button data-bind="click: addItem">Add</button></span>
<div data-bind="foreach: items">
<span data-bind="text: $data"></span>
</div>
--
ko.validation.rules['duplicate'] = {
validator: function (item, array) {
return array.indexOf(item) == -1;
},
message: 'Value already exists!'
};
ko.validation.registerExtenders();
var ViewModel = function() {
var self = this;
self.items = ko.observableArray();
self.newItem = ko.observable().extend({duplicate: self.items});
self.addItem = function() {
if (self.newItem().length > 0 && self.newItem.isValid()) {
self.items.push(self.newItem());
self.newItem(null);
}
};
}
ko.applyBindings(new ViewModel());
</p>