Jason Maggard
Jason Maggard

Reputation: 1672

knockout.js - Computed or observable

I have an application that allows our customers to come to our website, get a quote, and then do payback analysis, etc...

There are two sections... The "quote" section and the "payback" section.

I am using knockout to sync fields.... So when the customer comes in and says they need a 10 x 10 unit, we quote them $4,000. This value is copied to the "payback" sheet as Cost. We then deduct energy savings credits, investment tax credits, etc... To come up with "Net Investment".

As long as users follow every step just the right way, everything works.

Now, what happens if a user already has a ballpark on what they plan to spend on one of our units? They don't know they need a 10x10 unit, they just know they have $5,000 to invest and want to see if this investment has a good payoff. So, this sample user skips the quote part and just wants to input their assumed price and get some numbers.

My View Model is set up thus:

self.height = ko.observable('<?php echo $height; ?>'),
self.width = ko.observable('<?php echo $width; ?>'),
/* Math simplified to remove gobbeldygook */
self.cost = ko.computed(function () {return (self.height() * self.width()) * 40;}),

How do I set up "cost" so that it computes automatically when height and width are supplied but also is editable and changeable via the UI?

Thank you very much for your help.

Upvotes: 3

Views: 329

Answers (1)

Adam Rackis
Adam Rackis

Reputation: 83356

Knockout makes this easy with writeable computed observables. You can provide a read function, that returns the value when the user accesses it, like you already have, but also provide logic to occur when a value is written.

Based on your setup, it looks like you want the write portion of the cost computed to set appropriate values for height and width.

self.cost = ko.computed({
    read: function () { return (this.height() * this.width()) * 40; },
    write: function(value) { /* your logic here to set height and width */ },
    owner: self
});

The full docs are here, about 30% down:

Upvotes: 3

Related Questions