1

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?

Community
  • 1
  • 1
Alvaro
  • 40,778
  • 30
  • 164
  • 336
  • 1
    try this instead http://jsfiddle.net/hY5T2/145/ . cheers – super cool Jul 13 '15 at 15:19
  • valueUpdate just updates the observable when the key is pressed (as specified in your code). You can try subscribing the observable and check the necessary logic there. – G_S Jul 13 '15 at 15:23
  • most imp thing although your observable gets updated after `afterkeydown` but `change` works differently which fires only when focus is lost . – super cool Jul 13 '15 at 15:28

1 Answers1

3

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);
shammelburg
  • 6,974
  • 7
  • 26
  • 34