knockout.js - 在 KnockOutJS 中按 ID 查找

标签 knockout.js

鉴于以下情况,我如何取回 id 10?

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.arrayFirst 的尝试和 ko.utils.arrayForEach我失败了。

编辑

这现在有效,请参阅选定的答案。

关于加载顺序和 AJAX 的问题意味着这不能正常工作。

最佳答案

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

只要记住使用 self.children()到达底层数组。

关于knockout.js - 在 KnockOutJS 中按 ID 查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15294914/

相关文章:

使用 setInterval 的 javascript 自动刷新不起作用

grails - 如何进行 knockout 验证本地化工作

knockout.js - knockout - 当 'with' 绑定(bind)未定义时显示占位符

javascript - Knockout JS 数组为空或无法检索值?

php - 将 json 传递给 View 模型时保持安全

javascript - DOM 节点因 knockout foreach 而泄漏

javascript - 如何使用基本 KO 可观察数组来更新绑定(bind)到选择选项下拉列表的多个计算可观察数组

javascript - 使用 $.getJSON 获取时如何编辑 observableArray 数据?

html - 使用 knockout js 实现 html5 拖放照片,durandal 2.0

knockout.js - 在 foreach 完成渲染后,knockoutJS 执行回调