Knockout在observableArray中计算了observable

时间:2014-05-02 13:58:21

标签: javascript jquery knockout.js knockout-2.0

是否可以在observableArray中包含一个对象,该对象是同一对象中其他可观察对象的计算值?我有以下数组:

self.drug_costs_table = ko.observableArray([
        {
            label: ko.observable('salad'),
            cost_per_dose: ko.observable('123'),
            administrations: ko.observable('9'),
            discount: ko.observable('10'),
            cost_per_year: ko.computed(function () {
                // administrations * cost per dose
            })
        }
]);

observableArray将在HTML中动态构建,最后一列是药物成本x管理。是否可以在数组中包含此值,或者必须在数组外部进行某些操作才能计算cost_per_year?

这是我的HTML:

<!-- ko foreach: drug_costs_table -->
    <div class="row">
        <div class="grid_4"><label data-bind="text: label"></label></div>
        <div class="grid_2"><input class="total-val" data-bind="decimal: cost_per_dose"></div>
        <div class="grid_2"><input data-bind="number: administrations"></div>
        <div class="grid_2"><input data-bind="percentage: discount"></div>
        <div class="grid_2"><input class="total-val" data-bind="decimal: cost_per_year"></div>
    </div>
<!-- /ko -->

对此的任何帮助/建议将不胜感激;我仍然是淘汰赛的新手!

小提琴:http://jsfiddle.net/VWc8e/

2 个答案:

答案 0 :(得分:4)

有可能。但我认为你最好为药物成本实体定义一个视图模型。

function drugCot(label, cost_per_does, administrations, discount) {
   var self = this;
    self.label = ko.observable(label),
    self.cost_per_dose = ko.observable(cost_per_does),
    self.administrations = ko.observable(administrations),
    self.discount = ko.observable(discount),
    self.cost_per_year = ko.computed(function () {
         return  self.administrations() *  self.cost_per_year();
    })
}

然后你可以在包含self.drug_costs_table的视图模型中使用它来增加新的成本。

self.durg_costs_table.push(new drugCost('salad', 123, 9, 10));

修改

每当您现在更新self.administrations或self.cost_per_year observable时,您的cost_per_year计算将会更新。

var drugCost1 = new drugCost('salad', 123, 9, 10);
self.durg_costs_table.push(drugCost1);
drugCost1.administrations(15);
// after this line of code cost_per_year will contian new value and will notify all the subscribers and rerender bound html elements

答案 1 :(得分:1)

是的,可以在KO可观察数组中包含KO计算的可观察量。如果计算仅使用数组中同一对象的其他变量,则不必在数组外部完成任何操作。

self.drug_costs_table = ko.observableArray([
        {
            label: ko.observable('salad'),
            cost_per_dose: ko.observable('123'),
            administrations: ko.observable('9'),
            discount: ko.observable('10'),
            cost_per_year: ko.computed(function () {
                return parseInt(this.administrations(),10) * parseInt(this.cost_per_dose(),10);
            }, this)
        }
]);

修改

来自@ MyP3uK的答案应该是您首选的方式