Thoughts from the Wet Coast

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

It’s a Knockout: 8 - Observable Arrays of Observables

Category: JavaScript
Last Modified: May 2 2017
Mar 20 2014

Its been a while since I posted a blog in my Knockout series.  In the last couple of posts in this series we reviewed how Knockout implements the concept of Observable Arrays.  Observable Arrays support the idea of detecting when objects are added and removed from the array.  For a complete solution though we actually will want the array to contain observable objects so we can also detect when changes are made to each item.

Figure 1 shows the TaskViewModel.  This object will represent a single task.  Each property is defined as a knockout observable

Figure 1: The TaskViewModel

image

Now instead of defining our observable array using object literals like we did in Figure 1 of part 6 of this series, we will create the TasksViewModel as shown in Figure 2.

Figure 2: Creating an Observable Array of Observables

image

We now have two view models, one for the collection and one for a single task.  Functions and properties that manipulate the collection we will add to the TasksViewModel,  while functions and properties that manipulate a single task we will add to the TaskViewModel.

In a similar manner we can modify the “addtask” function introduced in Figure 1 of part 7 as shown in Figure 3.

Figure 3: Updating the addTask function

image

We don’t need to make any changes to the removeTask function we used in part 7.

So that’s the basics of working with observable arrays of observables.  In the next blog in the series I will show how we can use knockout to switch between different views of our data, so we can build an add/edit form.

Disclaimer

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

Categories

Tags