Read A SharePoint List Item Using KnockoutJS

Introduction

 
In this article, I will provide information on how to read a SharePoint List Item using Knockout JS. Note that this article is not for beginners and it needs a developer with a background in Knockout JS
 
Below are the components used in this document:
  1. Knockout JS
  2. SharePoint Online
  3. Visual Studio Code
In my recent project, we received a request on implementing a requirement using Knockout JS. The requirement was to read a SharePoint Online list item and display the same on the SharePoint Page using Knockout JS. Below is a step-by-step way to achieve the same. We need to create 3 files, as we know that Knockout JS follows the MVVM principle. All these 3 files would be uploaded to the _catalog/masterpage so that it can be then used inside a Content Editor Webpart and then that Content Editor webpart can be inserted into a SharePoint Page. To get more information on the basics of KnockOut JS and CRUD operation in MVC application you can refer to the article published by Akhil at this link.
  1. DisplayItem.html – holds the HTML tags to be displayed on the SharePoint page
  2. DisplayItem.js – holds the observable for the items to be displayed.
  3. Utilities.js – has methods to pull list item value from SharePoint 

Knockout JS Files

 
Create a text file
 
Name it as “DisplayItem.html” file. Open this file using Visual Studio Code.
 
Insert the below code into it
 
This code would put the binding in place which would hold the incoming SharePoint List Item value
  1. <div class="container">  
  2.    <span data-bind="text: DisplayText()"></span>  
  3. </div>  
  4. //---- Below line to refer the javascript file inside html page to allow bindings-----------//   
  5. <script> document.write("<script src='/sites/testingJ/_catalogs/masterpage/DisplayItem.js"'></script>"); </script>  
Save your HTML file and now create another text file. Name it as “DisplayItem.js”. Open this file using Visual Studio Code.
 
Note
The name of the js file is the same as what we mentioned inside the HTML file 
 
Insert below code
 
This would declare a observable for the text to be displayed on the HTML page. We need to pull the List Item from SharePoint and populate the lKeys.TestMeanMatch
  1. DisplayText: ko.observable(_lKeys.TestMeanMatch)  
Insert the below code which gets the value from SharePoint list based on a key.
  1. /*Get configuration values by keys*/  
  2. var GetListValue = function(key) {  
  3.     var listName = “Configuration”;  
  4.     var _query = this.BuildQuery({  
  5.         select: "Id,Key,Value",  
  6.         filter: getValueFilter(key),  
  7.         top: $.type(key) === "array" ? key.length : "1",  
  8.     });  
  9.     var _url = constants.rootSiteUrl + "/_api/web/lists/getbytitle('" + _listName + "')/items?" + _query;  
  10.     return spSendRequest(_url);  
  11. };  
  12. /*Send request to server*/  
  13. var spSendRequest = function(url, method, data, digest) {  
  14.     UpdateFormDigest(_spPageContextInfo.webServerRelativeUrl, _spFormDigestRefreshInterval);  
  15.     return $.ajax({  
  16.         url: url,  
  17.         data: data,  
  18.         contentType: "application/json;odata=verbose",  
  19.         method: method ? method : "GET",  
  20.         headers: {  
  21.             "Accept""application/json; odata=verbose",  
  22.             "X-RequestDigest": digest ? digest : $("#__REQUESTDIGEST").val(),  
  23.         },  
  24.         error: function(data) {  
  25.             errorFunc(data, url)  
  26.         }  
  27.     });  
  28. };  
  29. var getValueFilter = function(key) {  
  30.     var _filter = "";  
  31.     if ($.type(key) === "array") {  
  32.         if (key[0]) _filter = "Key eq '" + key[0] + "'";  
  33.         if (key.length > 1)  
  34.             for (var i = 1; key.length > i; i++) _filter += " or Key eq '" + key[i] + "'";  
  35.     } else { // filter contains single key  
  36.         _filter = "Key eq '" + key + "'";  
  37.     }  
  38.     return _filter;  
  39. };  
Add the below code for init methods to call the above-mentioned method:
  1. //#region Init Methods  
  2. var init = function() {  
  3.     initViewModel();  
  4.     initBindData();  
  5. };  
  6. var initBindData = function() {  
  7.     ko.applyBindings(vm, document.getElementById(_lConstants.bindingContainer));  
  8. };  
  9. var initViewModel = function() {  
  10.     //load data of page  
  11.     loadPageData();  
  12. };  
  13. var loadPageData = function() {  
  14.     //start load functions here  
  15.     GetListValue();  
  16. };  
  17. //#endregion  
Save all your files. Upload them into your SharePoint site _catalog/MasterPage folder. 
 
Create a SharePoint Page, insert a Content Editor webpart into it. Edit the webpart and put the DisplayItem.html file URL into this webpart.
 
Save the Webpart and open the new page in a new Browser. The value will get displayed from the SharePoint List Item.
 
That is it. I hope you have learned something new from this article and will utilize this in your work.


Similar Articles