是否可以在 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 -->
对此的任何帮助/建议将不胜感激;我对于 knockout 还是个新手!
fiddle :http://jsfiddle.net/VWc8e/
最佳答案
这是可能的。但我认为您最好为药品成本实体定义一个 View 模型。
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 的 View 模型内部使用它来添加新成本。
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
关于javascript - observableArray 中可观察值的 knockout 计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23429977/