This series is going to be broken down in to six parts and should be enough to show you how you can leverage the existing MVVM skills you acquired while building XAML and apply those to building HTML application with KnockoutJS.
Series Table of Context
- Setting Up the Data Context (this post)
- Working with Observable Properties
- Working with Observable Arrays
- Handling User Click Events
- Handling Binding Context Changes
- Changing UI Appearances Based on Bindings
One of the key tenants to MVVM in XAML is the ability to set up a data context and binding. This post is going to be dedicated to comparing and contrasting the way you handle setting up your binding context in XAML versus Knockout.
How to set up the data context in XAML:
The image above illustrates a very typical and easy way to bind your data context to your view. All we have done is created an instance of our view model and pushed it into the view's DataContext. Once the line above has been executed, all the bindings in your view will be updated and you are cooking with fire.
How do we accomplish the same goal in Knockout?
How to set up the data context in Knockout:
The image above is the one-to-one equivalent to setting up your data context in KnockoutJS.
Breaking down this code:
- We are creating a self-executing function. You can think of this as the constructor for the HTML page (this analogy is a stretch but it works).
- We then create an instance of our ViewModel.
- We call ko.applyBindings and provide our view model. This is the line of code that binds our ViewModel to our view.
As you can see, setting up your data context in Knockout is very similar to setting up the data context in a XAML application.
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.
Until next time.