Double Binding with Knockout JS

KnockoutJS is a great MVVM library for Javascript. If you haven’t seen it before, learn!

With KnockoutJS, it’s easy to bind two different elements to a single observable.

1
2
<input data-bind="value:amount"></input>
<div data-bind="text:amount"></div>

But it’s a little more complicated if you want to bind a single element to two different observables.

You can try this, but it won’t work:

1
<input data-bind="value:amount, value:otherAmount"></input>

The first binding, amount, will be ignored, and only the second binding, otherAmount, will work.

The solution is to make one binding in markup and the second one with code (or just do both bindings in code).

1
<input data-bind="value:amount"></input>
1
2
3
ko.applyBindingsToNode(theInputElement, {
value: otherAmount
});

Then both bindings will work, and both observables will stay in sync with the element in the DOM.