我正在尝试使用其中一个项的属性值在可观察数组中查找值。以下是一些示例代码:
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
我的问题:获取related_item的name属性以显示项目的related_id当前显示位置的最佳方法是什么?
答案 0 :(得分:2)
像这样的JSFiddle:Fiddle
我所做的是将item和related_item“对象”放入ViewModel中,以便我可以引用它们。有两种可能的解决方案:
JS:
self.item = function (data){
var itm = this;
itm.id = ko.observable(data.id);
itm.name = ko.observable(data.name);
itm.related_id = ko.observable(data.related_id);
//Possible solution 1
itm.related_item = ko.observable(data.related_item);
//Possible solution 2
itm.related_item_name = ko.computed(function() {
tmp = '';
$.each(self.related_items(), function(idx, elem) {
if (elem.id() === itm.related_id()) {
tmp = elem.name();
return false; //break out of the $.each loop
}
});
return tmp;
});
};
HTML:
<ul data-bind="foreach: items">
<li data-bind="text:name"></li>
<li>Cousin: <span data-bind="text:related_id"></span></li>
<li>(soln 1) Cousin: <span data-bind="text:related_item().name()"></span></li>
<li>(soln 2) Cousin: <span data-bind="text:related_item_name"></span></li>
</ul>
如果你没有其他约束,我宁愿做第一个方法并传递整个对象而不是ID。