Retrieve List Items Using Knockout.js with SharePoint REST API

Recently, I’m trying to use Client side object model or java script whenever possible. I’m sure there are multiple ways to retrieve List items, but in this scenario I will use SharePoint REST API and utilizing Knockout view model to display the list of items.

Prerequisite

  • Includes jquery.min.js to Style Library
  • Includes knockout.js to Style Library
  • Includes ko-sp.js to Style Library
  • Create Majors list
    ko1
  • Create Courses list
    ko2
  • Create Students list
    ko3
Solution

  • Edit a Page and Insert Content Editor webpart
    ko4
  • Edit Content Editor Source and insert below code:
    <script src="/Style%20Library/jquery-1.11.0.min.js"></script>
    <script src="/Style%20Library/knockout-3.1.0.js"></script>
    <script src="/Style%20Library/ko.sp-1.0.min.js"></script>
    <div id="restStudentDiv">
    	<table width="900px">
    		<thead>
    			<tr>
    				<th>SID</th>
    				<th>Name</th>
    				<th>Major</th>
    				<th>Courses</th>
    				<th>Status</th>
    			</tr>
    		</thead>
    		<tbody data-bind="template: { name: 'templateStudent', foreach: Items }" />
    	</table>
    </div>
    <script type="text/html" id="templateStudent">
    	<tr>
    		<td data-bind="text:SID"></td>
    		<td data-bind="text:Title"></td>
    		<td data-bind="spLookup:Major,defaultValue:'NA'"></td>
    		<td data-bind="spLookup:Courses,multi:true,defaultValue:'NA',dataFormat:'/'"></td>
    		<td data-bind="spChoice:Status"></td>
    	</tr>
    </script>
    <script type="text/javascript">
    	function StudentModal() {
    		var self = this;
    		self.Items = ko.observableArray([]);
    		$.getJSON(_spPageContextInfo.webAbsoluteUrl + "/_vti_bin/listdata.svc/Students?$expand=Major,Courses",
    		function (data) {
    			if (data.d.results) {
    				self.Items(ko.toJS(data.d.results));
    			}
    		}
    		);
    	}
    	ko.applyBindings(new StudentModal(), restStudentDiv);
    </script>
    
Result
ko5
Advertisements

Tagged: , , , , , , , , ,

One thought on “Retrieve List Items Using Knockout.js with SharePoint REST API

  1. […] will use my existing students list from my previous post for this example. I also want to makes the background color of each student different based on the […]

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: