【发布时间】:2016-11-07 16:42:33
【问题描述】:
以下是我想要达到的目标的示例。当我使它不可见时,我需要清除页面模型中的密码并且不知道该怎么做。
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script type="text/javascript" src="knockout-3.4.0.js"></script>
<script type="text/javascript" src="knockout.validation.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();" />
<script type="text/javascript" >
var pageModel;
ko.validation.init({
registerExtenders: true,
messagesOnModified: true,
insertMessages: false,
parseInputAttributes: true,
messageTemplate: null
}, true);
//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);
//this field is only required when visible
self.Password = ko.observable('').extend({ required: { onlyIf: function () { return self.PasswordVisible(); }, message: 'Password Invalid' } });
self.errors = ko.validation.group(self);
};
//The method calls on click of button
function validateModel() {
alert(pageModel.errors().length);
alert(pageModel.Password());
}
//create new instance of model and bind to the page
window.onload = function () {
pageModel = new ViewModel();
ko.applyBindings(pageModel);
};
</script>
</body>
</html>
我在计算 PasswordVisible 时无法清除,因为尚未按执行顺序创建 Password 属性。我无法交换它,因为这会导致我的扩展器出现问题以进行所需的验证。
【问题讨论】:
-
我已经用第二个问题回滚了您的编辑,因为据我所知,这是一个新的、单独的(但相关的)问题?如果需要链接到这个问题,请随时在 SO 上发布另一个问题,并解释它是如何分开/不同的。这使得其他有类似问题的人更容易找到解决方案,并保持这个特定线程的精简和干净。
标签: knockout.js knockout-validation