Sync: observables

by Jakub Jedryszek

HTML

<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-debug.js"></script>
<input type="text" data-bind="value: name1" /><span data-bind="text: name1"></span>
<br />
<input type="text" data-bind="value: name2" /><span data-bind="text: name2"></span>
<br />
<input type="text" data-bind="value: converted" /><span data-bind="text: converted"></span>

JavaScript

var ViewModel = function () {
    self = this;
    this.name1 = ko.observable("ku");
    this.name2 = ko.observable("ba");
    this.converted = ko.observable("kuba");
};

var vm = new ViewModel();

vm.name1.subscribe(function (newValue) {
    vm.converted(newValue + vm.name2());
    console.log("updated name2");
});

vm.name2.subscribe(function (newValue) {
    vm.converted(vm.name1() + newValue);
    console.log("updated name1");
});

vm.converted.subscribe(function (newValue) {
    vm.name1(newValue.substring(0,2));
    vm.name2(newValue.substring(2,4));
});

ko.applyBindings(vm);