Drew H
Drew H

Reputation: 4739

Add 2 numbers then subtract numbers depending on checkbox

Here is the jsfiddle of what I'm trying to do:

http://jsfiddle.net/5MxwV/1/

I'm kind of stuck because I've found out that you can't type into a dependent observable and get it to update. Basically you have 2 numbers. You add them together 4 + 5 = 9. Now when you hit a checkbox(or if it's possible to do it without checkbox), you disable the second number(5), and enable typing into final number(9). So you can type into the last box where the 9 is and the forumla would do 9 - 4 and that would give you the second number. So you can change 9 to a 10 and it would be 10 - 4 = 6.

   // Here's my data model
var viewModel = { 
    firstNum : ko.observable(4),
    lastNum : ko.observable(5),
    reverse : ko.observable(false)
};
viewModel.add = ko.dependentObservable(function () {

    return parseInt(viewModel.firstNum()) + parseInt(viewModel.lastNum()); 
});

ko.applyBindings(viewModel); // This makes Knockout get to work



  <p>First Number: <input data-bind="value:
 firstNum , valueUpdate:'afterkeydown'" /></p>
<p>Next Number <input data-bind="value: lastNum, valueUpdate:'afterkeydown', disable : reverse" /></p>
<p>Last Number:<input data-bind="value: add, valueUpdate:'afterkeydown', enable : reverse" /></p>

<p>Subtract : <input type="checkbox"  data-bind="checked: reverse" ></p>

<br />
<p data-bind="text: ko.toJSON(viewModel)"></p>

Upvotes: 0

Views: 1130

Answers (2)

RP Niemeyer
RP Niemeyer

Reputation: 114792

You will want to look into using a writeable dependentObservable for this situation.

It might look like:

viewModel.add = ko.dependentObservable({
    read: function() {
       return parseInt(this.firstNum(), 10) + parseInt(this.lastNum(), 10)
    },
    write: function(newValue) {
       this.lastNum(parseInt(newValue, 10) - parseInt(this.firstNum(), 10));
    },
    owner: viewModel
});

So, the idea is that your read function returns the value and the write function intercepts the writes and allows you to reverse your logic and update the appropriate observable.

http://jsfiddle.net/rniemeyer/jsZde/

Upvotes: 2

photo_tom
photo_tom

Reputation: 7342

You did not configure your dependentObservable correctly. You have to pass in the viewmodel itself as a parameter. Then inside the dependentObservalbe, you use "this" to refer to viewmodel.

I've updated the fiddle at http://jsfiddle.net/photo_tom/5MxwV/2/

Upvotes: -1

Related Questions