Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ko.utils.arrayFirst always returns null when not handling else block with non-empty string

This works correctly:

  self.getById = function(id) {
        return ko.utils.arrayFirst(self.PostArray(), function(item) {
            if (item.postId === id) {
                return item;
            }
            else {
                return 'not found';
            }
        });
    };

    console.log(self.PostArray().length);
    console.log(self.getById(170));

But if I put return '' or return null in else block I always get null, why is that?

like image 621
formatc Avatar asked Jan 19 '14 20:01

formatc


1 Answers

You're not using arrayFirst correctly. arrayFirst expects a function that returns true or false, evaluating each item. The first item for which the function returns true is returned. Here's how it should look:

self.getById = function(id) {
    return ko.utils.arrayFirst(self.PostArray(), function(item) {
        return item.postId === id;
    }) || 'not found';
};

Basically return 'not found' if item is falsey (null in this case most likely).

See this article for more information on the various utility functions in KnockoutJS.

like image 91
Andrew Whitaker Avatar answered Oct 29 '22 02:10

Andrew Whitaker