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:
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:
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: . I prefer to pass the reference to the child though.