Knockout Circular Reference (Simple Currency Converter)

I'm new to Knocout.JS so I have no idea how to accomplish my problem. Let's say I want to write a little currency converter.

<div>
    Rate: <input type="text" data-bind="value: Rate" />
</div>
<div>
    USD: <input type="text" data-bind="value: Dollar" />
</div>
<div>
    EUR: <input type="text" data-bind="value: Euro" />
</div>

My model is:

var viewModel = function() {
    this.Rate = ko.observable(0);
    this.Dollar = ko.observable(0);
    this.Euro = ko.computed(function() {
        return this.Dollar() * this.Rate();
    }, this);
}    
ko.applyBindings(new viewModel());

So I want to make sure that every textbox's change event updates another. For example if Dollar is updated I want to update Euro too.

  • Changes in Rate will update Euro
  • Changes in Dollar will update Euro
  • Changes in Euro will update Dollar

Here is my playground: http://jsfiddle.net/gnL4we9z/

Answers


You can make your Euro computed writable and update your Dollar property in its write function:

this.Euro = ko.computed({
    read: function () {
        return this.Dollar() * this.Rate();
    },
    write: function (value) {
        this.Dollar(value / this.Rate());
    },
    owner: this
});

Demo JSFiddle.


Need Your Help

Transformation cannot be added to style in Angular directive in IE only

javascript css angularjs internet-explorer

I have created an angular directive that creates a photo gallery. Sometimes the images have to be rotated, which I am doing through the CSS transform property (appended to the style in the directi...

Record and replay javascript

javascript javascript-events record replay

I know it is possible to record mouse movements, scrolling and keystrokes. But what about changes to the document? How can I record changes to the document?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.