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:
At the bottom of the Default.aspx page put the following code:
In the App.js file (under Scripts) folder place the following script:
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 >Step4: Your App Module
var viewModel = new window.MyApp.ViewModel();
viewModel.load();
ko.applyBindings(viewModel);
</script>
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
Post a Comment
Feel free to give constructive feedback or let me know if it was helpful.