2

我正在尝试使用其中一项的属性值在可观察数组中查找值。这是一些示例代码:

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 的名称属性以显示项目的related_id 当前显示在哪里的最佳方法是什么?​</p>

4

1 回答 1

2

像这样的JSFiddle在这里:小提琴

我所做的是将 item 和 related_item “对象”放入 ViewModel 中,以便我可以引用它们。有两种可能的解决方案:

  1. 将 related_item 本身传递给 item 对象,而不仅仅是 id。
  2. 遍历related_items 数组。

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。

于 2012-10-30T03:20:38.487 回答