2013-03-08 30 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