Knockout - StackOverflow 8764550 - Referring to a parent object from a computed function
http://stackoverflow.com/questions/8764550/using-a-computed-value-that-accesses-a-function-in-the-parent-viewmodel-in-knock
HTML
<script src="https://github.com/SteveSanderson/knockout/raw/master/build/output/knockout-latest.debug.js"></script>
<ul data-bind="foreach: parts">
<li>
<p data-bind="text: name"></p>
<p data-bind="text: manufacturer().name"></p>
</li>
</ul>
JavaScript
function Item(id, name) {
this.id = id;
this.name = ko.observable(name);
}
function Part(name, manufacturerId, parent) {
this.name = name;
this.manufacturerId = manufacturerId;
this.manufacturer = ko.computed(function() {
return parent.getManufacturer(this.manufacturerId);
}, this);
}
function ViewModel(items) {
var self = this;
self.items = ko.observableArray(items);
self.getManufacturer = function(manId) {
return ko.utils.arrayFirst(self.items(), function(item) {
//return ko.utils.stringStartsWith(item.id, manId);
return item.id === manId;
});
};
self.parts = ko.observableArray([new Part("Computer", 1, self), new Part("Fast Computer", 2, self), new Part("Router", 3, self)]);
}
ko.applyBindings(new ViewModel([new Item(1, "Dell"), new Item(2, "HP"), new Item(3, "Cisco")]));