你可以
HasErrors
ko.computed
自动创建对所使用的任何可见项的订阅。但它可能会触发一些不必要的重新评估。。。
ko.extenders.Validate = function(target, validateOptions) {
target.HasErrors = ko.computed(function() {
// Create subscription to newValue
var newValue = target();
// Create subscriptions to any obs. used in required
var required = validateOptions.required();
var validationType = validateOptions.validationType;
if (ko.unwrap(required)) {
switch (validationType) {
case "Text":
return newValue == "";
}
};
return false;
}, null, {
deferEvaluation: true
});
return target;
};
请注意,您也不需要将
PasswordVisible
在函数中可以观察到以执行它;你可以使用
ko.unwrap
相反
这是我在代码中的方法。当密码中有一个值(clearvia
self.Password('')
触发另一个验证)。
var pageModel;
var i = 0;
ko.extenders.Validate = function(target, validateOptions) {
target.HasErrors = ko.computed(function() {
console.log("validating " + ++i);
// Create subscription to newValue
var newValue = target();
// Create subscriptions to any obs. used in required
var required = validateOptions.required();
var validationType = validateOptions.validationType;
if (ko.unwrap(required)) {
switch (validationType) {
case "Text":
return newValue == "";
}
};
return false;
}, null, {
deferEvaluation: true
});
return target;
};
//The model itself
var ViewModel = function() {
var self = this;
self.Name = ko.observable('');
self.AlreadyUser = ko.observable(false);
//computed variable that sets the visibility of the password field. I have to clear the password when am making it invisible
self.PasswordVisible = ko.computed(function() {
return !this.AlreadyUser();
}, this).extend({
notify: 'always'
});
//this field is only required when visible
self.Password = ko.observable('').extend({
Validate: {
required: function() {
return self.PasswordVisible()
},
validationType: "Text"
}
});
self.PasswordVisible.subscribe(function(newVal) {
self.Password('');
});
self.HasErrors = ko.computed(function() {
return self.Password.HasErrors();
}, self);
};
//The method calls on click of button
function validateModel() {
console.log(pageModel.HasErrors());
}
//create new instance of model and bind to the page
window.onload = function() {
pageModel = new ViewModel();
ko.applyBindings(pageModel);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
Name:
<input type="text" data-bind="value:Name" />
<br />Already A User:
<input type="checkbox" data-bind="checked:AlreadyUser" />
<br />New Password:
<input type="password" data-bind="value:Password,visible:PasswordVisible" />
<br />
<input type="button" value="Submit" onclick="validateModel();" />