Knockout.JS: Triggers based on changes in an observable

gzost picture gzost · Sep 1, 2012 · Viewed 32.8k times · Source

I have an input element which is bound to a knockout observable:

<input type="text" data-bind="value: myText, valueUpdate: 'keyup'" />

This updates the observable on each keyup. I now want to trigger additional events when the value changes.

The following does this in principle:

this.myTextTrigger = ko.computed( function () {
    console.log( this.myText() );
}, this );

However, it seems somewhat clunky. It also triggers on the initial instantiation of the template, where I only want to handle changes after that. Is there an official/easier way to trigger events based on changes to observables?

Answer

meze picture meze · Sep 1, 2012

Use subscribe:

this.myText.subscribe(function (newText) {
   console.log(newText);
});

If you want to reuse this trigger you can consider writting a custom binding.