|The Knockout for the XAML developer course helps XAML developers, whether you’re a WPF or Silverlight developer, take their existing MVVM skills and transition them to the exciting world of HTML development.|
This series is going to be broken down into 6 parts and should be enough show you how you can leverage your existing MVVM Skills you acquired while building XAML and apply those to building HTML applications with Knockout JS.
Series Table of Contents
- Setting up the Data Context
- Working with Observable Properties
- Working with Observable Arrays (this post)
- Handling User Click Events
- Handling Binding Context Changes
- Changing UI Appearances based on Bindings
After we have set up our view model and bound it to our markup thing, what we would typically do is start setting up our observables. In my prior post, we took a look at how to work with Observable Properties, but what about working with an array of items?
When working with XAML applications, you would set up your observable collections as seen below.
How to setup an Observable Collection in XAML
The code above is pretty straightforward. We have a property, which is of type ObservableCollection. When we set up our property, we set up our backing field along with raising property change messages each time the array is populated. One thing not illustrated here is what happens when an item is added or removed from the collection. That is because this is handled by the ObservableCollection class. Each time something is added or removed, the underlying collection type will raise the notifications for us.
Now that we remember how to set up an observable collection in XAML, how would we accomplish the same using KnockoutJS?
How to setup an Observable Array in KnockoutJS
The image above is a 1 to 1 match for setting up an Observable Collection Knockout vs XAML.
If we break down our code (this code is written in Typescript)
- We first declare our property, in our case ReminderGuests
- We tell the Typescript Complier this is an ObservableArray of type UpcomingReminderModel (not needed if not using Typescript)
- We initialize our property via Knockout using ko.observableArray() (I like to init the array as empty out of convention)
We now have an observable array declared. How do we use it in our Markup?
To use an Observable Array in Knockout, what we need to do is use the ‘foreach’ binder, and away we go.
If you want to learn more about how your XAML MVVM skills transfer to HTML Development, watch my Pluralsight Course – Knockout for the XAML Developer.