Html JavaScript Development using MVVM

Shawn Wildermuth talks about using KnockoutJS framework to develop a MVVM application:

KnockoutJS is a framework that allows me to use HTML-based data binding markup to describe my UI, CSS to describe what the design looks like and JavaScript to tie the data to the data binding. The is chiefly accomplished through the concept of observable objects. For example, I created a new JavaScript ‘class’ called gameModel in my view.js by creating members using the observable method on the knockout (e.g. ko) object:

// view.js
$(document).ready(function () {

  function gameModel() {
    this.name = ko.observable();
    this.id = ko.observable();
    this.genre = ko.observable(); this.releaseDate = ko.observable();
    this.price = ko.observable();
    this.imageUrl = ko.observable();
  };
  …
});

 
The observable call returns an object that not only can store a property, but let the KnockoutJS binding stack know when the property changes (two way binding). In order to use the gameModel ‘class’, I created a view model to store a collection of gameModels like so:
 
// Define Main ViewModel
var theViewModel = {
  games: ko.observableArray([]),
  ...
};

The games property of the view models ‘class’ will hold the current list of games that are shown in the UI. The observableArray object is like the observable object but it notifies the data binding stack when a collection changes. The goal here is to have the view model load the games from the REST service and as the collection changes, the HTML should change to react to that. No more manually creating/destroying parts of the markup.

In order to make this work, we must use the data binding syntax in the HTML code:

<div data-bind="foreach: games">
  <div class="game-block">
    <div>
      <img data-bind="attr: { src: imageUrl, alt: name }" /></div>
    <div class="game-name" data-bind="text: name">
    </div>
  </div>
</div>

For more: http://wildermuth.com/2011/11/20/Using_MVVM_on_the_Web_with_KnockoutJS