Friday, January 02, 2015

Knockout binding in SharePoint 2013 SharePoint-Hosted App

Today I was trying to make Knockoutjs work with SharePoint Hosted Apps in a way that is manageable and extensible. I assume you already know Knockout JS and know how to create a basic SharePoint-Hosted App.

There can be many ways using which KO can be plugged into an application but here here is what I think would work well for SharePoint-Hosted Apps considering async JSOM calls:

Step1: Add Knockout JS
Just download the js file and paste inside the Scripts folder. Refer it in your Default.aspx page.

Step2: Add html binding
In the Default.aspx page of SharePoint 2013 Hosted put the following code in the "<p id="message">" tag:
Welcome <span data-bind="text: username"></span>
Step3: Apply KO Bindings
At the bottom of the Default.aspx page put the following code:
    <script >
        var viewModel = new window.MyApp.ViewModel();
Step4: Your App Module
In the App.js file (under Scripts) folder place the following script:
'use strict';
(function () {
    //create new if its not alredy initialized.
    window.MyApp = window.MyApp || {};
    window.MyApp.ViewModel = function () {
        //assign this to me so that it could be accessed with the functions/event handlers
        var me = this;
        this.context = SP.ClientContext.get_current();
        this.spUser = ko.observable();
        this.username = ko.computed(function () {
            //as soon as spUser is populated, username also gets loaded
            if (me.spUser()) {
                return me.spUser().get_title();
            return '';
        this.load = function () {
            //loading the user will load all its dependent bindings
            var user = me.context.get_web().get_currentUser();
            me.context.executeQueryAsync(function () {
Note that "spUser" as observable and "username" is a computed property that is based on spUser. As soon as spUser is loaded, username also loads itself.

Above mentioned point is the key to the above implementation. It utilizes the "Dependency Tracking". This way all the dependencies on SharePoint can be resolved asynchronously.

No comments:

Post a Comment

Feel free to give constructive feedback or let me know if it was helpful.