This is a multi-part excerpt series from my PluralSight course Knockout for the XAML Developer
| || |
|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 show you can leverage your existing MVVM Skills you acquired while building XAML based and apply those to building HTML application with Knockout JS
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 setup 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 vs Knockout.
How to setup the Data Context in XAML
The image above illustrates a very typical, and easy 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 views 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 when using KnockoutJs?
How to setup the Data Context in Knockout Js
The image above is the 1 to 1 equivalent to setting up your data context in Knockout Js.
Breaking down this code.
- We are creating a self executing function, you can think of this as the constructor for the HTML page (that is a stretch analogy 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 which 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 based applications.
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
Till next time,
08-10-2013 6:14 AM