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;
}
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.
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.
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.
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
Seems like ko.utils.arrayFirst
or ko.utils.arrayFilter
will fit your needs better then your current approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With