简体   繁体   中英

Knockout.js computed

I am using Knockout.js to develop a calculator. I am facing a situation that I don't know how to handle. In the below example, everything works fine when the user enters a product and value and the values are saved in the DB. But when the user comes to edit this page, my requirement is to show all the values the user entered along with the total. But when the user changes something in the product or quantity, the total should change as expected.

We now store the total in DB and total could be changed by some admin users.In this case,is there a way we can override the computed value when the user goes to the edit page but when the user changes product or quantity,then the compute should happen with the latest values from product and quantity.

Help is appreciated.

var TsFoundationDeviceModel = function(product,qty) {
var self = this;
self.product = ko.observable();
self.quantity= ko.observable();
self.computedExample = ko.computed(function() {
   return self.product() * self.quantity() ;
});}

My HTML code looks like

<input name="product" data-bind="value:product">
<input name="value" data-bind="value:value">
<input name="total" data-bind="value:computedExample"/>

You have to bind the view to the screen. Check out this fiddle and give it

 var TsFoundationDeviceModel = function(product,qty) {
var self = this;
self.product = ko.observable(product);
self.quantity= ko.observable(qty);
self.computedExample = ko.computed(function() {
 return self.product() * self.quantity() ;
});}

ko.applyBindings(new TsFoundationDeviceModel(2,3));

http://jsfiddle.net/Z6VPV/5/

When you reference observables within your computed you need to treat them like functions so instead of return self.product * self.quantity ; you would use return self.product() * self.quantity();

Fiddle: http://jsfiddle.net/SAV9A/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM