当它不可见时清除它

时间:2016-07-05 18:33:31

标签: knockout.js knockout-validation

以下是我想要实现的目标示例。我需要清除页面模型中的密码,当它变得不可见时,我不知道该怎么做。

<!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属性。我无法交换它,因为这会导致我的扩展程序出现问题以进行必要的验证。

1 个答案:

答案 0 :(得分:2)

你可以这样做:

function readURL() {
        if(window.File && window.FileReader && window.FileList && window.Blob){
            //All the File APIs are supported.
        }else{
            alert('The File APIs are not fully supported in this browser, try to update it or get a new one here.');
            }
        }

    function handlefiles(event){
        var files = event.target.files;
        var i,f;

        var form_data = new FormData(); 
        for(var i = 0; f=files[i];i++){
            form_data.append(i,f);
            if(!f.type.match('image.*')){
                continue;   
            }

            var reader = new FileReader();

            reader.onload = (function(the_file){
                return function(e){
                    var li = $("<li/>").attr('class','thumbnailupic');

                    li.html('<img class="thumb" src="'+e.target.result+'" title="'+ the_file.name+ '"/><div class="progress_bar"><div class="percent"></div></div><div class="cancel_read" title="remove">x</div>');

                    li.appendTo($("#here"));

                };
            })(f);

            $("#start_upload").click(function(e) {  
            $.ajax({
                xhr: function() {
                    var xhr = new window.XMLHttpRequest();          
                    xhr.upload.addEventListener("progress", function(evt) {
                        if (evt.lengthComputable) {
                            var percentComplete = Math.round((evt.loaded / evt.total) * 100);

                            // this shows me the progress of each file being uploaded 
                            console.log(percentComplete);

                            if(percentComplete){
                                if(percentComplete <= 100){
                                    //I want each "li" that is automatically generated containing their respective progress par being filled up as the upload happens but I'm stuck....since I don't know how


                                    //this is what i had in mind.... I was thinking about looping but it's useless since I don't know how to go to the next element after the first file it's sent....
                                    //$("#here li:eq("+i+")").find('.percent').css({"width":"" + percentComplete + '%' + "",'height':'100%','background-color':'#906'});
                                }


                            }

                        }
                   }, false);

                   return xhr;
                },
                type: 'POST',
                url: "process_upload.php",
                data: form_data,
                contentType: false,
                cache: false, 
                processData: false,
                success: function(data){
                    //Do something on success
                }
            });

            });

            reader.readAsDataURL(f);
        }
    }

    $("#upload_pics").click(function(e) {
        if($("#start_upload").length == 0){
            var start_upload = $("<div/>").attr('id','start_upload').html("start upload");
            start_upload.insertAfter($(this));
        }
        if($("#upics").length == 0){
            $("<input>").prop({"type":"file","multiple":true,"id":"upics","name":"pics[]"}).trigger('click').change(function(e) {
                readURL();  
            },handlefiles);
        }
    });

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

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

修改

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

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