Link the two observables in knockout.js

I have two simple observables, for example,

val1 = ko.observable("input1"); val2 = ko.observable("input2"); 

and I want them to act as one, so when one of them changes, the other changes.

I know that in the general case it is better to use only one observable and associate it with several dom elements. But in my case, these observables live in different patterns and objects, so they cannot be one variable.

I am currently signing one observable to another and vice versa:

 val1.subscribe(function(v) { val2(v); }); val2.subscribe(function(v) { val1(v); }); 

However, when you change the value of one observable, it updates the second, but causes a ripple effect and updates the first again, to infinity.

How can I establish a two-way binding between two separate observables, which sets the value of one when the other changes, without causing an infinite loop?

+4
source share
2 answers

You can do something like this:

 vm1 = { val1: ko.observable('input1'), otherProperty: ko.observable('more') } vm2 = { val2: vm.val1, otherProperty: ko.observable('data') } 

Both vm1.val1 and vm2.val2 resolve the same observable and therefore the same value.

0
source

Sethi's answer will work, but it may be better with calculated observables.

Example: http://jsbin.com/exipuq/1/edit

 var viewModelA = function(){ this.myVal = ko.observable(); }; var viewModelB = function(otherViewModel){ this.compVal = ko.computed(function(){ return otherViewModel.myVal(); }); }; // create a new viewmodel like normal var vma = new viewModelA(); // pass the instantiated view model // into the new one you're creating var vmb = new viewModelB(vma); 
0
source

Source: https://habr.com/ru/post/1438150/


All Articles