Integrating knockout.js and SharePoint 2010

Recently I watched the following MIX conference session about konckout.js by Steve Sanderson
Even if you never have heard of knockout.js I defenitly recommend you to take a look at it, they placed a lot of effort in the documentation that is available here.

knockout is a library that can be used side by side with jQuery and other libraries but it makes your live as a web developer much easier, interested? :)
The documentation on the website states:
Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and maintainably.

Basically it allows you to data-bind values to html elements, when the javascript object value changes… the value in the html element changes automatically with it. This can be done without knockout, but it would cost you a lot of event binding and maintenance.

The example I prepared is a sandboxed solution that adds the required javascript files and a demo page to the site assets library. It uses the buitlin SharePoint REST service to retrieve the values and when you select a specific file, display the details of the file.

Step 1: Provision the javascript references as custom actions in the head of each page.


Step 2: The demo page content
This demo page is not the perfect startup example, because it combines jQuery, Rest, knockout viewmodel and knockout templates in 1 page.
In my opinion it is the combination of these 4 elements that makes it for us as SharePoint developers very interesting.

Page Actions:
1) We use jQuery to call the REST service and when the results are returned we bind them to a helper class.
2) A viewModel is created and the helper class objects are added as an observableArray.
3) The data-bind attribute is set to a select html element, this will set the values of the observableArray as elements in the combobox.
4) The applyBindings method is called on the knockout object, this will make sure that all the values are set to the correct bindings.

The content of the sharepoint page should look like this:

The example solution can be downloaded here:
  download tomvangaever.knockoutjs

Hope this helps,

VN:F [1.9.22_1171]
Rating: 9.1/10 (7 votes cast)
VN:F [1.9.22_1171]
Rating: +4 (from 4 votes)