How to call a function again and again using knock

2019-09-01 09:57发布

I have this knockout code.

self.newPatient = ko.asyncCommand({

     execute: function(complete) {
        var isValid=$('#addPatientForm').parsley( 'validate' );
        if(isValid){
        var patientJson=ko.toJSON(self.patient());
        formdata.append("json",patientJson);
        //self.enableButton(false);
     var imagepath= $.ajax({
                url: projectUrl+"newPatient", 
                type: "POST",
                data: formdata,
                processData: false,
                contentType: false,
                success: function (res) {
                    formdata = new FormData();
                    imagepath=res;
                    var length=self.patients().length;
                    var patient=self.patient();
                //  self.enableButton(true);
                }
     });    


     } 
     },
     canExecute: function(isExecuting) {
         return !isExecuting && isDirty() && isValid();
     }
 });

This is my html inputfields

<div class="control-group">
            <label class="control-label" for="inputIcon">Username :</label>
            <div class="controls">
                <div class="input-prepend">
                    <span class="add-on"><i class="icon-hand-right"></i></span>
                    <input class="span8" type="text" data-bind="value: username" name="username" data-required="true" data-trigger="change" data-remote="${pageContext.request.contextPath}/isUserNameExists" data-remote-method="GET">
                </div>
            </div>
        </div>
        <div class="control-group">
            <label class="control-label" for="inputIcon">Password :</label>
            <div class="controls">
                <div class="input-prepend">
                    <span class="add-on"><i class="icon-hand-right"></i></span>
                    <input class="span8" type="password" data-bind="value: password" name="password" data-required="true" data-trigger="change">
                </div>
            </div>
        </div>

and this is my button

<button class="btn btn-primary"
                                                    data-bind="command: $root.newPatient, activity: $root.newPatient.isExecuting">
                                                    <i class="icon-ok icon-white"></i> Save
                                                </button>

when I press the save button then execute: function(complete){.....} is called and inside this function

var isValid=$('#addPatientForm').parsley( 'validate' );

is called which checks form validity and if the form is invalid then isValid is false and hence the ajax is not called.

I want to call

 var isValid=$('#addPatientForm').parsley( 'validate' );
        if(isValid){.....} 

when any of the input field is changed .So can any body please suggest me how to do?

2条回答
萌系小妹纸
2楼-- · 2019-09-01 10:03

You could write your own bindingHandler:

ko.bindingHandlers.parsley = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        var isValid = valueAccessor();
        var $form = $(element).closest('form');
        $(element).change(function() {
            isValid($form.parsley('validate'));
        });
    }
};

And in your ViewModel:

self.isValid = ko.observable(false);

And then:

<form ...>
    <input data-bind="parsley: isValid, ..." />
</form>

See http://jsfiddle.net/sjroesink/ksqXx/

Edit

Without being able to reproduce your error, or an actual line where the error occurs, I cannot help you. Try using Chrome's Developer tools to see where the error occurs:

track error

查看更多
该账号已被封号
3楼-- · 2019-09-01 10:17

You could use the subscribe function of your observable to run code:

username.subscribe(function () { isValid=$('#addPatientForm').parsley( 'validate' ); }
password.subscribe(function () { isValid=$('#addPatientForm').parsley( 'validate' ); }

Update after your comment: Here is what I would do:

<div id='koRoot'>
    <input type='text' data-bind='value: username' />
    <input type='text' data-bind='enable: enableButton,value: password' />
    <input type='button' data-bind='command: newPatient' value='Go!' />
</div>
...

And the js:

    var callNewPatient = function () {
        if (self.awaitingValidation()) self.newPatient.execute();
    }

    this.username.subscribe(callNewPatient);
    this.password.subscribe(callNewPatient);

    this.newPatient = ko.asyncCommand({
        execute: function (complete) {
            self.isValid(self.username() === 'me' && self.password() === 'pass');
            if (self.isValid()) {
                self.awaitingValidation(false);
                alert("Valid!");
            } else {
                self.awaitingValidation(true);
            }
        },
        canExecute: function (isExecuting) {
            return self.isValid();
        }
    });

http://jsfiddle.net/nyothecat/LkaEJ/1/

查看更多
登录 后发表回答