Skip to content Skip to sidebar Skip to footer

How To Call A Function Again And Again Using Knockout

I have this knockout code. self.newPatient = ko.asyncCommand({ execute: function(complete) { var isValid=$('#addPatientForm').parsley( 'validate' ); if(isVali

Solution 1:

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...><inputdata-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

Solution 2:

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'>
    <inputtype='text' data-bind='value: username' />
    <inputtype='text' data-bind='enable: enableButton,value: password' />
    <inputtype='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) {
            returnself.isValid();
        }
    });

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

Post a Comment for "How To Call A Function Again And Again Using Knockout"