I’m trying to look up a value in an observable array using the value of a property of one of the items. Here is some example code:
HTML:
<ul data-bind="foreach: items">
<li data-bind="text:name"></li>
<li>Cousin: <span data-bind="text:related_id"></span></li>
</ul>
JS:
var item = function (data){
this.id = ko.observable(data.id);
this.name = ko.observable(data.name);
this.related_id = ko.observable(data.related_id);
}
var related_item = function(data){
this.id = ko.observable(data.id);
this.name = ko.observable(data.name);
}
var ViewModel = function(){
this.items = ko.observableArray([
new item({id:1,name:'thing1',related_id:1}),
new item({id:2,name:'thing2',related_id:2})
]);
this.related_items = ko.observableArray([
new related_item({id:1,name:'cousin it'}),
new related_item({id:2,name:'cousin fred'})
]);
}
ko.applyBindings(new ViewModel);
Fiddle with code above: fiddle
My question: What is the best way to get the related_item’s name property to show where the item’s related_id is currently being shown?
Something like this JSFiddle here: Fiddle
What I did was put the item and related_item “objects” into the ViewModel so that I could reference them. There are 2 possible solutions:
JS:
HTML:
If you have no other constraints, I’d just rather do the first method and pass the entire object in instead of the ID.