Posted by: R Manimaran | April 27, 2015

Applying Dynamic Templates in KnockoutJs in Table

I was exploring the Knockout JS for my data-binding with my SharePoint 2013 REST API output. My requirement was to bind my REST API output as a Table format and do the CRUD Operation on the table itself.

Knockout 3.0 offers the SimpleGrid to bind your output to a grid view with pagination. But in the same row itself I need to provide the option to do the edit/Save/ Delete operations. So I went for normal table bindings.

Knockout offers the template binding which I used to dynamically changing the binding logic (view/Edit Mode).


<table class="tab-table">
 <tbody data-bind="template :{name:currentTemplate,foreach:articles}">

Read-Only Template Script:

<script id="readOnly" type="text/html">
<td><span data-bind="text:title"></span></td>
<td><span data-bind="text:content"></span></td>
<td><input type="button" value="Edit" data-bind="click: function() { viewModel.selectedMode($data) }"/></td>
<td><input type="button" value="Delete"/></td>

Edit Template Script:

<script id="editMode" type="text/html">
       <td><input type="text" data-bind="value:title"></input></td>
       <td><input type="text" data-bind="value:content"></input></td>
       <td><input type="button" value="Cancel" data-bind="click: function() {viewModel.reset();}"></input></td>
       <td><input type="button" value="Save"></input></td>

In the above I have created two templates, one to apply my read-only databinding and another to have textbox to do edit operations.

View Model:

var viewModel = {
    articles: [{
        id: 1,
        title: "KnockOut Templating",
        content: "Content for Knockout goes here."
    }, {
        id: 2,
        title: "SharePoint 2013 REST API",
        content: "Content for SharePoint."
    }, {
        id: 3,
        title: "Knockout with SharePoint",
        content: "Content for knockout and SharePoint."
    selectedTemplate: ko.observable("readOnly"),
    selectedMode: ko.observable(),    

viewModel.currentTemplate = function (tbl) {
    return tbl === this.selectedMode() ? 'editMode' : this.selectedTemplate();

viewModel.reset = function (t) {

After applying the above template, by default it will load my read-only output.(added some CSS to change the look of the table)


On Clicking the Edit button my edit mode template will be applied and allow the user to do editing. On clicking the cancel button it will change the template back to the read-only.




  1. very useful

  2. […] […]

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s


%d bloggers like this: