IT:AD:Knockout.JS

Summary

In one line: blank empty Visual Studio 2012 MVC projects include a reference to IT:AD:Knockout.JS (basically meaning that even if you are not using it, everybody else will be…).

Reasons: Variable Models

A very interesting issue with MVC came to light in the last project. For a while, I couldn't pin it down, until I had a chat with Gareth R. He remembered seeing a post somewhere that I think hits it on the head:

The problem with MVC is...the Model.

Heresy, I know. As Model is an integral part of MVC, and MVC is the bees knees, it's better than ASP.NET, yada yada. That's true…until you have to deal with variable models (ie models that have more or less properties, depending on other criteria), at which point, one ends up writting tons of code for handling the edge cases (validation, nullable ViewModel properties, etc.).

The framework just doesn't support the concept of flexible models, and it quickly becomes costly. Yet, responsive UI's, reactiving according to either Workflow, User permissions, or other UI layout rules, demands variable Models.

Note: for all its faults, classic ASP.NET didn't have this problem simply because there was no sense of Model -- just individual Fields.

Include Src File

Example:

<script src="...knockout-1.2.js" text="text/javascript"></script>

Create a View Model

Example:

 <script>
 //Map as ViewModel:
 var viewModel= 
 {
   //Binding to property directly,
   //but it won't automatically get updated from UI changes:
   first:"Bart",
   //Or use ko method to make it so: 
   last: ko.observable("Smith")
 }
 </script>

View Markup

  • Ref Markup.
  • Create a UI side model (see Model)
  • Bind UI elements to the View Model, using the data-bind attribute:

Examples:

<p>First name: <span data-bind="text:first"/></p>
<p>Last name: <span data-bind="text:last"/></p>

Wiring up

Resources