Thoughts from the Wet Coast

The musings of an ASP.NET Developer from Canada's We(s)t Coast

It's a Knockout: 6 - Observable Arrays

Category: JavaScript
Last Modified: May 2 2017
Aug 16 2013

In previous posts in this series I introduced the concept of observables, and I referred to the concept of Observable Collections in Xaml (WPF and Silverlight) applications.  Knockout also supports the concept of observable collections, although because JavaScript only has one collection type they are observable arrays.

Just as an observable responds to changes in an object, an observable array responds to a change in the number of items in the array.  It tracks which objects are in the array - not the state of those objects.

Knockout handles observable arrays with the observableArray method.

Figure 1: An Observable Array

image

The syntax to create an observableArray is pretty much the same as the syntax to create an Array.  In fact an observableArray has most of the same methods as the Array object.

Now that we know how to create an Observable Array, how do we bind it to our view.  Knockout provides the “foreach” binding, which allows knockout to replicate the children elements for each member of the Observable Array - see Figure 2

Figure 2: The foreach binding

image

In this example the foreach binding is used to bind the Tasks array to a table.  The foreach element is placed on the element and the and its children are replicated for each object in the array. 

This approach could also be used on an unordered list - ul - or ordered list - ol tag to replicate each child li tag.

Note that the data-bind attributes in the child row refer to the properties of the object which is bound to that row by the foreach binding. 

The full listing is shown in Figure 3

Figure 3: Observable Arrays example

image

 

This renders the following in the browser.

image

As I mentioned at the beginning of this post, an Observable Array responds to changes in the number of objects in the array.  In the next post I will show how elements can be added and removed from the array.

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

Categories

Tags