您无法直接从 subBar 访问 viewModel 的变量 - 函数。
如果你像这样定义你的viewModel:
function vm() {
var self = this;
this.subBars = ko.observableArray ([
new subBar(initialWidth01, color01);
new subBar(initialWidth02, color02);
]);
this.subBarsTotal = ko.computed(function(){...});
...
}
var viewModel = new vm();
你可以调用它的属性:
function subBar (initialWidth, color) {
self.initialWidth = initialWidth;
self.width = ok.computed(function(){
var adjustedWidth = self.initialWidth() / viewModel.subBarsTotal() * widthOfBar;
return adjustedWidth;
}
self.color = color;
}
或者您可以像这样将 viewModel 的实例传递给 subBar:
function vm() {
var self = this;
this.subBars = ko.observableArray ([
new subBar(initialWidth01, color01, self);
new subBar(initialWidth02, color02, self);
]);
}
function subBar (initialWidth, color , vm) {
...
vm.subBarsTotal();
...
}
编辑 :
我稍微改变了你的代码。在定义的计算函数之后推送数组值。
检查这个JsFiddle 链接
function hundred_bar_section(width, color, dvm) {
this.hundred_width = ko.observable(width);
this.section_color = color;
console.log(dvm.hundred_bar_total()); // is now defined
}
function DashboardViewModel() {
var self = this;
this.hundred_bar_sections = ko.observableArray([]);
// adds the total current values of all hundred_bar_section widths
this.hundred_bar_total = ko.computed(function() {
var hundred_bar_length = self.hundred_bar_sections().length;
//console.log (hundred_bar_length);
var hundred_bar_added = 0;
for (var i = 0; i < hundred_bar_length; i++) {
hundred_bar_added += self.hundred_bar_sections()[i].hundred_width();
}
console.log(hundred_bar_added);
return hundred_bar_added;
});
this.hundred_bar_sections.push(new hundred_bar_section(100, "#f60", self));
this.hundred_bar_sections.push(new hundred_bar_section(200, "#6f0", self));
this.hundred_bar_sections.push(new hundred_bar_section(100, "#06f", self));
}
$(document).ready(function() {
var vm = new DashboardViewModel();
ko.applyBindings(vm);
})