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();
        viewModel.load();
        ko.applyBindings(viewModel);
    </script>
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.load(user);
            me.context.executeQueryAsync(function () {
                me.spUser(user);
            });
        }
    };
})();
Explanation:
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.

Comments

Popular posts from this blog

Unable to delete Shared Services Provider in SharePoint (MOSS)

The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.

Cannot add a SimpleContent column to a table containing element columns or nested relations