How can I use knockout's $parent/$root pseudovariables from inside a .computed() observable?
http://stackoverflow.com/questions/8640748/how-can-i-use-knockouts-parent-root-pseudovariables-from-inside-a-computed
by johnwun
HTML
<script src="https://github.com/downloads/SteveSanderson/knockout/knockout-2.0.0.debug.js"></script>
<ul data-bind="foreach: items">
<li data-bind="css: { selected: isSelected }">
<a href="#" data-bind="text: name, click: $root.selectedItem"></a>
</li>
</ul>
<hr/>
<div data-bind="text: ko.toJSON($root)"></div>
CSS
.selected { background-color: #f88; }
JavaScript
var Item = function(name, parent) {
this.name = ko.observable(name);
this.isSelected = ko.computed(function() {
return this === parent.selectedItem();
}, this);
};
var ViewModel = function() {
// here clicked object ref is passed implicitly to variable
this.selectedItem = ko.observable();
this.items = ko.observableArray([
new Item("one", this),
new Item("two", this),
new Item("three", this)
]);
};
ko.applyBindings(new ViewModel());