KO: two variables subscribing to each other

I do not know how to correctly formulate this question ... I want to have two variables that look at each other and change accordingly. One is decimal, the other is percentage.

I have one observable in my model. It gets the value from the server side.

self.varDecimal = ko.observable(valueFromServerSide);

This variable contains a decimal value. I need to show this variable in the input field (in fact it will be touchspin with user binding) and let the user edit it. However, I need the user to edit not a decimal value, but a percentage.

self.varPercents = ko.observable(); //should be = self.varDecimal * 100

So:

1), when the data is mapped to the server, I need to self.varPercentscalculate from self.varDecimal( self.varDecimal() * 100).

2) I need it to self.varPercentsbe displayed on the input (in fact it will be touchspin, but it will be later), and the user is allowed to change the percentage.

3) The user edits this percentage, and I want self.varDecimalto update accordingly (self.varPercents / 100). Later, self.varDecimal is sent back to the server.

Is this possible with some KO subscriptions or calculations or similar?

I know that I can live without it, for example, when I receive data, I can just calculate self.varPercents, but when sending data back to the server I can recount self.varDecimal, but I would like to know if this is possible through some knockout functions , because actually I have many fields like this, and I need some kind of general solution.

+3
source share
1 answer

http://knockoutjs.com/documentation/computedObservables.html#writeable-computed-observables

http://jsfiddle.net/QAe72/

this.percentage = ko.computed({
    write: function(value) {            
       this.decimal(value / 100);
    },
    read: function() {
        return this.decimal() * 100;
    }
}, this);
+5

All Articles