<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>
var Item = function(name, parent) { this.name = ko.observable(name); this.isSelected = ko.computed(function() { return this === parent.selectedItem(); }, this); }; var ViewModel = function() { this.selectedItem = ko.observable(); this.items = ko.observableArray([ new Item("one", this), new Item("two", this), new Item("three", this) ]); }; ko.applyBindings(new ViewModel());
.selected { background-color: #ccc; }
Sample here: http://jsfiddle.net/rniemeyer/BuH7N/
If all you care about is the selected status, then you can tweak it to pass a reference to theselectedItem
observable to the child constructor like: http://jsfiddle.net/rniemeyer/R5MtC/
If your parent view model is stored in a global variable, then you could consider not passing it to the child and using it directly like: http://jsfiddle.net/rniemeyer/3drUL/. I prefer to pass the reference to the child though.