Follow @endyourif rss Facebook LinkedIn

Knockout JS Foreach Loop Knockout JS Foreach Loop

Published on Jul 31, 2022

Knockout is an easy way to loop through observable arrays or standard array objects using a foreach data bind statement. Let's look at a concrete, in depth example.

Knockout.js is a JavaScript library that makes it easier to write reusable components in JavaScript. It provides a simple syntax for binding data to HTML elements.

This tutorial will show you how to use knockoutjs with a simple example of the foreach data binding with afterRender.

KO foreach binding example

In order to demonstrate how to use foreach binding, we will start by creating a very simple component. We will then bind some data to our component and display it in the DOM. Finally, we will add a button to remove the element from the DOM. Let's starting creating a simple example script within our HTML.

To begin, let's create a very simple component. This component will contain two text boxes and one button. It will also have a click handler attached to the button.

Add Javascript Library

We'll start by adding knockoutjs to our project. In order to do so we need to add the following script tag to our index.html file and we then need to initialize knockout with the ko object.

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
ko = require('knockout');

Bind Data with array item in our ViewModel

Once we've initialized ko with our Javascript, we can use it to bind data type to a view model with the following example. Let's say we wanted to display a list of names in a table. We would first define a view model.

var viewModel = {
names: ko.observableArray()
};

Run Code

Then we'd initialize our code using the following text Javascript syntax with our script type.

ko.applyBindings(viewModel);

We can then iterate through each name in the array by using a foreach loop. In this example I will leverage a ko comment binding to perform the foreach binding on our parameter of our ko.observablearray name. Inside the foreach binding I also use the basic data bind text with the $data value. This is similar to the `this` context with ko computed observables and subscribe when using the td data bind.

<table>
<tr>
<th>Name</th>
</tr>
<tbody>
<!-- ko foreach: names -->
<tr>
  <td><span data-bind="text: $data"></span></td>
</tr>
<!-- /ko -->
</tbody>
</table>

The data bind text does not have to go inside a comment. I actually commonly use the tbody data bind or a div data bind. Let me update the example text javascript with the new html foreach data.

<table>
<tr>
<th>Name</th>
</tr>
<tbody data-bind="foreach: names">
<tr>
  <td><span data-bind="text: $data"></span></td>
</tr>
</tbody>
</table>

TD data bind text HTML markup

In such data bind foreach, all observable array items are identified by HTML tags in loops. It is incredibly useful for importing tables. Foreach data can be integrated together with control flow bindings for our observable array with the td data bind text.

For what purpose do we use foreach binding in Ko?

The objective is: Foreach binding re-writes the markup in every column in an observable array and binds the corresponding markup to the array item. The software is particularly effective in rendering table and chart information.

What is data bind in HTML?

Data bind connects data from custom elements with properties and attributes from the local DOM (child DOM or targets). Host element, such as a div data bind, data is a property or subproperty represented in data paths or data that is generated using one or more paths in the text javascript array.

Tags: foreach | Knockout js Tutorial

About Jamie Munro

Welcome to my blog. I have been compiling articles since 2009! Below is a list of every post I've ever created. Some of my major focuses have been compiling the best source of jQuery tutorials on the Internet today. A recent focus of mine is now focusing on creating the best SQL Tutorials for Beginners, Intermediate and Advanced Users. This is a compiliation of all my experience about how to do common SQL commands to optimize for performance. As you might see from the links around here, I've also written and published 5 books. My first and last book are focused around ASP.NET MVC and Web API tutorials. The last book has a big focus on integrating Knockout.js as the MVVM for the front-end code. O'Reilly Media was so interested in Knockout.js that they actually commissioned me to write that book first as it is one of the only books dedicated entirely to this MVVM library. So if you're looking for the best Knockout.js tutorials, I've compiled the best list. My first book, even though it was self published, was on the PHP framework: CakePHP. I used this framework for years and many of my first ever exampes were all focused on CakePHP tutorials that provide so many fantastic PHP examples. There are so many Javascript tutorials out there, but I noticed that one of the things I work on most with Javascript is arrays. With this I've worked hard on compiling a big list of really advanced Javascript array examples. These array examples are amazing including how to group by, get distinct array elements and so many more. I've also dabbled a little bit with Node.js and during those experiments I definitely ran into some common errors like Can't set headers after they are sent, Solving No Access-Control-Allow-Origin with Node js and Express, and Uncaught ReferenceError: require is not defined. With these common errors I've compiled a list of Node.js tutorials that help solve these problems, but more importantly getting you started with the basics.