Note that there are some explanatory texts on larger screens.

plurals
  1. POConnecting Two Knockout Variables Together Without Causing Recursion
    primarykey
    data
    text
    <p>While developing code for a online calculator framework called <a href="https://github.com/gbmhunter/candy-calc" rel="nofollow">candy-calc</a>, I have two <code>ko.observables</code> called <code>calcVar1.selUnit</code> and <code>calcVar2.selUnit</code> which I want to connect together. By that I mean, if one changes, the other one will change, and vise versa. The way I have tried to go about this is to create two display variables calcVar1.dispSelUnit and <code>calcVar2.dispSelUnit</code>which are <code>ko.computed()</code>. These are bound to in the view, and they have different read/write functions as follows.</p> <pre><code> // Modified write function calcVar1.dispSelUnit = ko.computed({ read : function(){ console.log('Reading source var sel unit.'); // Return as usual return calcVar1.selUnit(); }, write : function(value){ // Write to both of them console.log('Writing ' + value + 'to both sel unit.'); calcVar1.selUnit(value); calcVar2.selUnit(value); }, owner : this }); // Modified write function calcVar2.dispSelUnit = ko.computed({ read : function(){ console.log('Reading destination var sel unit.'); // Make it equal to the source variables selected unit return calcVar2.selUnit(); }, write : function(value){ // Write to both of them console.log('Writing ' + value + 'to both sel unit.'); calcVar1.selUnit(value); calcVar2.selUnit(value); }, owner : this }); } </code></pre> <p>So basically, the <code>dispSelUnits</code> are acting as a intermediary to the real <code>selUnit</code> values below, and on write update both <code>selUnit</code> (<code>ko.observables</code>), while on read behave as normal. </p> <p>I can't see anything wrong with this logic. However, when running this, if I try and update <code>compVar1.dispSelUnit</code>, it enters a infinite loop where <code>compVar1.dispSelUnit</code> gets written then read, and then <code>compVar2.dispSelUnit</code> gets written and read, and then back again.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload