Search code examples
knockout.jsknockout-3.0knockout-3.2

Call function on input change with knockout.js (valueUpdate)


I'm trying to call a function when my input value gets updated. The function will validate the input value and set a flag to true or false which will be used in multiple elements in the DOM.

I have been trying the proposed solution here:

<input data-bind="event: { change: value_changed }, value: saved_value, valueUpdate: 'afterkeydown'" />

But it doesn't seem to work on afterKeyDown. It only calls the function on unfocus as you can see here: http://jsfiddle.net/imac/hY5T2/142/

What am I doing wrong?


Solution

  • Here is an update of your JSFiddle

    <input data-bind="value: demo, valueUpdate: 'afterkeydown'" />
    
    
    var viewModel = function () {
        var self = this;
    
        self.demo = ko.observable('');
        self.myFunction = function(){
            alert("fired");
        }
    }
    
    var VM = new viewModel();
    ko.applyBindings(VM);
    
    VM.demo.subscribe(function(){
        VM.myFunction();
    });
    

    I hope this is what you wanted??

    Thanks

    EDIT:

    Without subscriber. JSFiddle without subscriber

    var viewModel = function () {
    
        var self = this;
    
        self.demo = ko.observable('');
    
        self.myFunction = function () {
            alert("fired");
        }
    
        self.worker = ko.computed(function () {
            if (self.demo()) self.myFunction();
        }, this);
    }
    
    var VM = new viewModel();
    ko.applyBindings(VM);