Getting Started with Knockout on SharePoint 2013 Online (or on Prem)

Getting Started with Knockout on SharePoint 2013 Online (or on Prem)

This post explains the minimal steps to begin using Knockout with SharePoint. It does not attempt to explain how to use Knockout. For that you should start with the knockout tutorial. This example was developed on a free Office 365 developer site. You can sign up for your own SharePoint Developer site here, or use an existing on-Prem or cloud installation.

After you have created your SharePoint development environmet, create a new Team Site called KOTest.   From the Site Actions menu select Site contents.

siteContents

Then, at the bottom of the Site Contents page, click the new subsite link:

newSubsite

Name the site KO Test, set the URL name to KOTest and select the Team Site template:

newsite

After creating the Team Site, browse to it and  add two Document Library ‘apps’ – one called JavaScripts (that will hold your JavaScript  files) and one called CEWPSource (that will hold  the html templates that will be displayed in Content Editor Web parts). 

To Add the Libraries, select Site Content from the Site Actions menu:

siteContents

And then select add an app

addanapp

Then select the Document Library app:

DocumentLibrary

Name the Library JavaScripts:

addJavascriptsLibrary

Follow the same procedure to create a Document Library called CEWPSource.

Also add a Custom List App called Companies that will hold a list of company names. This will hold test Data (just a simple list) for the Knockout app:

addCustomList

Now download the knockout-2.2.0.debug.js and jquery-1.8.2.js  files and add them to the JavaScripts Library.

To create Knockout apps for SharePoint we need to create both JavaScript and Html files.  I’ve found it easier to work on these files if I open the SharePoint Library with explorer:

openWithExplorer

Then, when explorer has opened, I can right-click on any of the files and select Open With à Visual Studio 2012.

So once you’ve downloaded knockout-2.2.0.debug.js and jquery-1.8.2.js and uploaded them to your JavaScripts library, open that library in explorer. If you get this error:

err

Add the site to your trusted sites as instructed. If you still get the error, sign out of SharePoint, and then sign in again after checking the ‘Keep me signed in’ checkbox on the sign in page.

 signin

Now that you’ve got the JavaScript library opened in windows explorer, right –click in the right-hand panel and select New à Text Document.

newTextDoc

and rename the document to test.js. Then Open the file with Visual Studio 2012.
 openWithvs2012

Now that we’ve got the mechanics out of the way, we can start working on some Knockout. This document does not attempt to explain how to use knockout. For that you should start with the knockout tutorial.

Enter the following code into the test.js file:

$(document).ready(function () { LoadModel(); });

function LoadModel() {

    var vm = new ViewModel();

    ko.applyBindings(vm);

}

 

function ViewModel() {

    var self = this;

    self.companies = ko.observableArray([]);

    $.getJSON(“../_vti_bin/listdata.svc/Company”,

        function (data, textstatus, jqXHR) {

            for (index in data.d.results) {

                var result = data.d.results[index];

                var koItem = {};

                koItem.Title = ko.observable(result.Title);

                self.companies.push(koItem);

            }

        });

}

 

This is about the minimum we can code to create a Knockout ViewModel using SharePoint. 

The first line:

$(document).ready(function () { LoadModel(); });

 

calls jQuery and tells it to run the LoadModel method once the DOM has been loaded.

The LoadModel Method calls the ViewModel() constructor and assigns it to a local variable vm. It then calls ko.applyBindings(vm) to bind the data in the viewModel to the view (which we’ll define in a minute).

The ViewModel() Constructor first saves its context by assigning the ‘this’ object to a local variable ‘self’. It then creates a ko.observableArray() to hold the list of companies and calls jQuery’s getJSON method to get the data from the Companies list we created earlier in SharePoint.

In the GetJSON callback function, it loops over each of the results and for each one it creates a new JavaScript object called koItem. It then creates a ko.observable() using the Title it received from SharePoint and adds it to the koItem.  Finally it adds the koItem to the list of companies with self.companies.push(ko.Item).

 

Now that you’ve created the required JavaScript, create the html view. Open the CEWPSource document library in Explorer and add a new file called test.html. Then open the file in Visual Studio 2012 and past the following code.

<div>

    <h2>Companies</h2>

    <table data-bind=”template: {name: ‘commpanytemplate’, foreach: companies}”>

    </table>

    <script id=’commpanytemplate’ type=”text/html”>

        <tr>

            <td style=”width: 250px”>

                <span data-bind=”text:Title” />

            </td>

        </tr>

    </script>

</div>

 

The table tag uses a knockout template binding  to iterate over the list of companies we have in our  viewModel and for each one, render a <tr> that displays the Title of the company.  The data-bind attribute within the span uses the knockout text binding to display the actual text.

 

Now that you have created the necessary artifacts we need to deploy them to a SharePoint page. Navigate to the home page of the KOTest site, then click on the Page tab, and select Edit:

editPage

You first need to insert some links to the JavaScript file you’ve loaded into your JavaScripts Library, so  click the Embed Code icon: In the popup dialog enter the URL’s of your JavaScript files:

embedcode

In the popup dialog enter the URL’s of your JavaScript files:

<script  type=”text/javascript” src=”../javascripts/jquery-1.8.2.js”></script>
<script  type=”text/javascript” src=”../javascripts/knockout-2.2.0.js”></script>
<script  type=”text/javascript” src=”../javascripts/test.js”></script>

enerurls

Now you have your JavaScript file loaded on the page, so the only remaining task is to add the view. To do this select Web Part from the Insert Tab:

insertWebpart

And select a Content Editor Web Part (from the Media and Contents folder)

cewp

Click the OK button to insert the Web Part. Once you’ve inserted the Web Part you need to edit it so that you can tell it where to pull its content from:

 editwebpart

In the Content Editor Web Part Tool part tell it to load the html in your CEWPSource/test.html file. Enter the URL ‘../CEWPSource/test.html’ The ‘../’  is required because the page is loaded from the SitePages library within the site. The ‘../CEWPSource’ tells the browser to go up a level from where the page was loaded, to the site, and then select the CEWPSource Library. This URL may change depending on where your page is loaded from.

editorpart

Now if you browse to the home page, you should see the results:

done

Advertisements
This entry was posted in javascript, jquery, knockout, sharepoint. Bookmark the permalink.

3 Responses to Getting Started with Knockout on SharePoint 2013 Online (or on Prem)

  1. C. Marius says:

    Hi,

    Interesting post, thank you! Not to minimalize the importance of combining Knockout with REST in the new SharePoint 2013, but I assume you are aware there are other way, much easier to achieve event better results, such as using the JSLink on ListView web parts, or relying on Client-Side Rendering for advanced manipulation of the rendering for each Field.

    • russgove says:

      Hi,
      I’ve been playing around with JSLink and jsrender to customize some views. It seems to work great within the limits of Sharepoint (although the documentation seems a bit sketchy at the moment!).

      The power of knockout comes in handy when you want to enable users to update the data in the browser. While it’s not shown in this post, I do hope to have future posts that demonstrate this power.

      Also, when you have lookup columns in lists there are some limitations on which columns from the ‘child’ list can be included in the ‘parent’ list(like multiline text). Knockout overcomes these limitations.

      Perhaps the most compelling use of knockout in sharepoint 2013 will be in using it in conjunction with data that is not stored in lists. The new rest api can let us retrive info on Webs, sites,permissions, etc. which cant be easily exposed in a listview webpart.

      But if you’re just going to display the data, and maybe provide links to the EditForm, JSLInk would be the way to ho in my opinion.

      [side note: I think it would be interesting to create an XSLT Template that would just render the contents of a DVWP as JSON. Then we could just use pure javascript and plate library we choose to shape the html the way we want it)

  2. Leo says:

    Good post.

    $.getJSON(“../_vti_bin/listdata.svc/Company”, should be $.getJSON(“../_vti_bin/listdata.svc/Companies”,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s