To get started with the knockout spa library:

Include the spa.js file in your libraries (use the spa.min.js for production)

View the Full Walk-Through at Walkthrough using MVC 4 (beta) on Visual Studio 11

Use nuget "knockoutspa"  to add these packages!

Quick Tips to get started:

  • The entire spa library is in the spa. namespace
  • Create a DataContext first in your view model
  • Use the DataContext's AddSet method to connect to WebAPI Controllers
  • Use the DataSet's CreateView method to create Views which you consume in your view model.

About Entities (the core data item):

  • Entities are returned as spa.dataEntity
  • Your properties properties are exposed on the dataEntity's "Entity" property.
  • For Example:
    • In Web Api Controller you return Product { ID, Name}
    • In spa this appears as dataEntity.Entity.ID and dataEntity.Entity.Name properties.

About Views (the core view of your data):

  • Views have a Query property which composes your query
  • Views expose a ViewItems observable collection, which has the dataEntity items from your query
  • Views expose an AddItem method to add new items
  • Views expose a DeleteItem method to delete items
  • If your dataset is buffering changes Call the View's SaveAll method to commit your changes.  If you are not buffering changes, there is no need to ever call SaveAll.
  • If you are buffering changes, make sure you set overwrite to false when calling Refresh, or you will lose any pending changes.

Quick Example to get started:

var myapp = myapp || {};

myapp.viewModel = function () {
    var self = this;
    self.data = new spa.dataContext(true);
    self.set = self.data.AddSet("Products", "ID");
    self.view = self.set.CreateView();
    self.view.Query.filter = "Quantity " + spa.filterTypes.GreaterThan + " 0";
    self.view.Query.orderby.push(new spa.ordering("Price"));

    self.selectedItem = ko.observable();

    // Refresh our View
    self.view.Refresh();

    self.addItem = function () {
        self.view.AddItem(new spa.dataEntity({ 
ID: 0,
Name: "<New Item>",
Price: 0,
Quantity: 0,
Category: ""
})); }; self.deleteItem = function (item) { self.view.DeleteItem(item); }; self.save = function () { self.view.SaveAll(); }; self.refresh = function () { self.view.Refresh(false); }; return { Items: self.view.ViewItems, SelectedItem: self.selectedItem, Refresh: self.refresh, AddItem: self.addItem, Save: self.save, Delete: self.deleteItem, } }; $(document).ready(function () { ko.applyBindings(new myapp.viewModel()); });

In the Web Page you could bind like this:
<ul data-bind="foreach: Items">
  <li> 
      <span data-bind="text:Entity.ID"></span>
      <span data-bind="text:Entity.Name"></span>
      [<span data-bind="text:EntityState"></span>]
  </li>
</ul>

Last edited May 1, 2012 at 10:15 PM by rposener, version 7

Comments

zbrong Jun 5, 2012 at 12:39 AM 
good job ! I will waiting for it to grow up.