当前位置: 动力学知识库 > 问答 > 编程问答 >

knockout.js - KnockoutJS value not auto calculating

问题描述:

I have the following code:

View:

<table>

<thead><tr>

<th>Food</th><th>Quantity</th><th>Price</th><th>Total</th>

</tr></thead>

<tbody data-bind="foreach: lines">

<tr>

<td><input data-bind="value: name()" /></td>

<td><input data-bind="value: quantity()"></td>

<td><input data-bind="value: price()"></td>

<td data-bind="text: total()"></td>

</tr>

</tbody>

</table>

Viewmodel:

function line(name, quantity, price) {

var self = this;

self.name = ko.observable(name);

self.quantity= ko.observable(quantity);

self.price = ko.observable(price);

self.total = ko.computed(function(){

var x = (self.quantity() * self.price());

return x;

}, self);

}

function MyViewModel() {

var self = this;

self.lines = ko.observableArray([

new line("Steve", 2, 7),

new line("Bert", 5, 9)

]);

};

ko.applyBindings(new MyViewModel());

When I run it I get the correct initial printout, but when I change quantity or price on any line item, the total does not change, what am I missing here?

网友答案:

Your computed value would update properly, but you have bound your UI elements to the original values of the observables instead of the actual observables. Remove the parentheses and it should work.

e.g. Replace data-bind="text: total()" with data-bind="text: total"

分享给朋友:
您可能感兴趣的文章:
随机阅读: