javascript - Data binding within an object and to the DOM -


this extreme simplification of want build(loan interest calculator). have 3 fields. whenever 1 field changed, want others change in order satisfy algebraic equation:

a = b * c b = / c c = / b 

i think want bind these values object, i'm not sure how go this. here set have far:

var binder = {   a: 2,   b: 1,   c: 1 };  $('input[type=number]').on('change', function() {   var id = $(this).attr('id');   var value = id.val();   binder[id] = number($(this).val());     }); 

at point i've set corresponding key in object value of active field. run through bunch of case() statements like:

switch( id ) {   case :     binder.b = $(this).val()/binder.c;     binder.c = $(this).val()/binder.b;     break;     etc. } 

i need update field values. seems unsustainable, when number of fields grow, , computation becomes more complex. question twofold:

how bind fields' values object?

how bind object's values each other?

as @dbugger commented knockoutjs perfect this

var model = {    a: ko.observable(2),    b: ko.observable(1),    c: ko.observable(1)  };    ko.applybindings(model);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>  <input data-bind="value: a, valueupdate: 'afterkeydown'"> = (b x c) <span data-bind="text: b()*c()"></span><br />  b <input data-bind="value: b, valueupdate: 'afterkeydown'"> = (a / c) <span data-bind="text: a()/c()"></span><br />  c <input data-bind="value: c, valueupdate: 'afterkeydown'"> = (a / b) <span data-bind="text: a()/b()"></span><br />


Comments