2013-03-08 33 views
3

鉴于以下情况,我如何将id 10退出?通过ID在KnockOutJS中查找

function ChildListViewModel() 
{ 
    var self = this; 
    self.children = ko.observableArray([]); 

    self.children.push({id:20,name:"Jake"}); 
    self.children.push({id:10,name:"Jake"}); 

    self.find = function(id) 
    { 
     console.log(self.children().length); 
     setTimeout(function(){console.log(self.children().length);}, 500); 
     found = ko.utils.arrayFirst(self.children(), function(child) { 
      return child.id() === id; 
     }); 

     console.log(found); 

     return found; 
    } 

} 

我要像做

ChildVM.find(10); 

使用ko.utils.arrayFirstko.utils.arrayForEach都失败了我所有的尝试。

编辑

这就是现在的作品,看到所选的答案。

有关加载顺序和AJAX的问题意味着它没有像应该那样工作。

+1

arrayFirst应该工作,你怎么使用它? – 2013-03-08 13:20:45

回答

11
return ko.utils.arrayFirst(self.children(), function(child) { 
    return child.id === id; 
}); 

只记得使用self.children()去底层数组。

+0

虽然不是返回true,而是返回子对象? – 2013-03-08 13:23:16

+0

它返回与条件匹配的对象。 – 2013-03-08 13:23:52

+1

@jookoble传递给arrayFirst函数的参数函数(或者闭包)return * true *用于标识符合期望条件的项目(在本例中为“id”标识) - arrayFirst函数,基于关闭,返回匹配的第一个项目。 – Grim 2013-03-08 13:26:48