繁体   English   中英

在observableArray中计算可观察值的敲除

[英]Knockout computed of observables in observableArray

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

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/

有可能的。 但是我认为您最好为药品成本实体定义视图模型。

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观测值,您计算出的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

是的,可以在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的答案应该是您这样做的首选方式

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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