2
votes

I am trying to bind a grid with 3 fields in each row using Knockout.js: net price (textbox), tax amount (label), total price (textbox).

All fields are autocaltulated as soon as either net or total price changes. The calc is simple: net price = total price - tax amount; total price = net price + tax amount; tax amount = taxrate (const) * net price

These bindings for a single entity is demonstrated in this fiddle: http://jsfiddle.net/ruslans/yEDRT/

But how would I do it for a whole list in anobservable array i have no idea?

TaxRate is constant for each row but can be different (it comes from source data).

Plus. all numeric fields must be formatted to 2 decimal places, hence the function. this is what I've got so far:

<table>
    <thead>
        <tr>
            <th>&nbsp;</th>
            <th>Net Price</th>
            <th>Tax Band</th>
            <th>Tax Amount</th>
            <th>Total Price</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: OptionsModel.AvailableDealerFitOptions">
        <tr>
            <td>
                <label class="checkbox">
                    <input type="checkbox" class="optionCheck" /> <span data-bind="text: Description"></span>

                </label>
                <input type="hidden" class="optionTaxRate" data-bind="value: TaxRate" />
            </td>
            <td>
                <input type="number" min="0" max="99999999.99" step="0.01" data-bind="value: $root.formatNumber(NetPrice)" />
            </td>
            <td> <span data-bind="text: TaxBandDisplayName"></span>

            </td>
            <td> <span class="uneditable-input" data-bind="text:  $root.formatNumber(TaxAmount)"></span>

            </td>
            <td>
                <input type="number" min="0" max="99999999.99" step="0.01" data-bind="value: $root.getTotalDealerFitOptionPrice($data)" />
            </td>
        </tr>
    </tbody>
</table>

http://jsfiddle.net/ruslans/k7tK3/2/

have you done anything like it before? If so, could you give me pointers on how this could be achieved, please?

1

1 Answers

2
votes

Your issue is that you are using an observable array of objects - this will get recomputed only when the size of the array changes, not the contents of the array!

What you want is an array of ko.observable. Then your ko.computed function will be revaluated when the individual values change. If you have a dynamic list of items to sum, then use an observable array of observables.

Hope that helps!