Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find by ID in KnockOutJS

Tags:

knockout.js

Given the following, how do I get id 10 back out?

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;
    }

}

I want to do something like

ChildVM.find(10);

All attempts using ko.utils.arrayFirst and ko.utils.arrayForEach have failed me.

EDIT

This now works, see selected answers.

Issues around loading order and AJAX meant this was not working as it should do.

like image 700
Jake N Avatar asked Mar 08 '13 13:03

Jake N


1 Answers

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

Just remember to use self.children() to get to the underlying array.

like image 69
RP Niemeyer Avatar answered Sep 28 '22 03:09

RP Niemeyer