StackOverflow
http://stackoverflow.com/questions/11795010/accessing-external-values-from-within-knockout-js-observablearray-item-construct/11796407#11796407
by gurkavcu
HTML
<script src="http://jquery-json.googlecode.com/files/jquery.json-2.2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.2.1/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.3.2/knockout.mapping.min.js"></script>
<div id="hundred_bar" class="widget hundred_bar">
<div class="hundred_bar_bar" data-bind="foreach: hundred_bar_sections">
<div class="hundred_bar_section" data-bind="style: { width: (hundred_width() + 'px'), backgroundColor: section_color }">a</div>
</div>
</div>
JavaScript
function hundred_bar_section(width, color, dvm) {
this.hundred_width = ko.observable(width);
this.section_color = color;
console.log(dvm.hundred_bar_total()); // is undefined
}
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);
})