Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I break or continue knockout's arrayforeach?

Tags:

knockout.js

This is sample code. I want to break (or continue) knockout's ko.util.arrayForEach.

ko.utils.arrayForEach(items, function (item) {
    if (...) break;
    if (...) continue;
}
like image 369
Oguz Karadenizli Avatar asked Jul 25 '12 11:07

Oguz Karadenizli


People also ask

How do I break ko utils Arrayforeach?

Just use ko. utils. arrayFirst that will execute a function on the array and and will return/break as soon as the the function evaluates to true.

Can we break forEach loop?

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

For what purpose do we use forEach binding in Ko?

Purpose. The foreach binding duplicates a section of markup for each entry in an array, and binds each copy of that markup to the corresponding array item. This is especially useful for rendering lists or tables.


2 Answers

Looks like you can't. Here's the source of arrayForEach (from utils.js on the KO GitHub page)

arrayForEach: function (array, action) {
    for (var i = 0, j = array.length; i < j; i++)
        action(array[i]);
},

However Knockout provides ko.utils.arrayFirst that will execute a function against each item in our array and return the first item where the function evaluates to true. Similar to the filteredItems computed observable, we can create one that returns the first match from our search field:

//identify the first matching item by name
viewModel.firstMatch = ko.computed(function() {
    var search = this.search().toLowerCase();
    if (!search) {
        return null;
    } else {
        return ko.utils.arrayFirst(this.filteredItems(), function(item) {
            return ko.utils.stringStartsWith(item.name().toLowerCase(), search);
        });
    }
}, viewModel);

More details can be found here http://www.knockmeout.net/2011/04/utility-functions-in-knockoutjs.html

like image 151
bmode Avatar answered Oct 01 '22 12:10

bmode


Seems like ko.utils.arrayFirst or ko.utils.arrayFilter will fit your needs better then your current approach.

like image 28
Madman Avatar answered Oct 01 '22 12:10

Madman