在 Observable 不可见时清除它

Clearing the observable when it's invisible

下面是我试图实现的示例。我需要清除 pagemodel 中的密码,当我让它不可见时,我不知道该怎么做。

<!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 属性 尚未按执行顺序创建。我不能交换它,因为这会导致我的扩展器出现问题,无法进行所需的验证。

你可以简单地这样做:

<input type="password" data-bind="value:Password, visible:AlreadyUser" />

根本不需要计算。然后在你的 ViewModel 中:

self.Password = ko.observable('').extend({ 
    required: { 
      onlyIf: function () {
        return self.AlreadyUser(); 
      }, 
      message: 'Password Invalid' 
    } 
});

编辑

我想我在原来的回答中没有回答你的问题。如果您想在用户取消选中(或选中)绑定到 self.AlreadyUser 的复选框时实际清除 self.Password() ,那么您可以使用 subscribe:

self.AlreadyUser.subscribe(function(newVal){ 
   // reset password every time the value of self.AlreadyUser() changes
   self.Password(''); 
});