Skip to content

Instantly share code, notes, and snippets.

@garima2510
Last active December 28, 2015 18:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save garima2510/7540964 to your computer and use it in GitHub Desktop.
Save garima2510/7540964 to your computer and use it in GitHub Desktop.
Demo of Knockout.js with Sharepoint 2013 - Adding Items
.tableStyle {
border-collapse:collapse;
border: 1px solid black;
text-align:center;
width:50%;
padding:15px;
}
.messages {
display:none;
font-weight:bold;
}
#success {
color:green;
}
#failure {
color:red;
}
'use strict';
//global variables
var hostWebUrl;
var appWebUrl;
var listItems;
var list;
var context;
var completeCountryList;
$(document).ready(function () {
//get the url of app web and host web
hostWebUrl = QS("SPHostUrl");
appWebUrl = QS("SPAppWebUrl");
LoadData();
});
//class for saving the countries and their states
function CountryList(countryName, stateName, isUpdated) {
var self = this;
self.CountryName = countryName;
self.StateName = stateName;
//IsUpdated is just to keep tab of rows that are added/removed from the table. This is not a SP column
self.IsUpdated = isUpdated;
}
//View Model to combine data from list into the format which view expects
function CountryListViewModel() {
var self = this;
self.Countries = ko.observableArray([]);
self.AddCountries = function (countryName, stateName, isUpdated) {
self.Countries.push(new CountryList(countryName, stateName, isUpdated));
//hide success message
$("#success").hide();
}
self.RemoveCountries = function (country) {
self.Countries.remove(country);
//hide success message
$("#success").hide();
}
//Update SP list with the changes in view model
self.UpdateSPList = function () {
var changedCountries = [];
var emptyValues = false;
//create array of only those rows that are updated
$.each(self.Countries(), function () {
if (this.IsUpdated == true) {
//if either of the country or state name is blank skip the entry
if (this.CountryName.length > 0 && this.StateName.length > 0) {
$("#tdError").hide();
changedCountries.push(this);
this.IsUpdated = false;
}
else {
emptyValues = true;
}
}
});
//show error message if even one of the entry is blank
if (emptyValues) {
$("#failure").text("Empty values are not updated in sharepoint");
$("#failure").show();
}
else {
$("#failure").hide();
}
//if there are no updates
if (changedCountries.length == 0) {
alert("No Items to update");
}
else {
SubmitDataToSP(changedCountries);
}
}
}
//function to update corresponding sharepoint list
function SubmitDataToSP(changedCountries) {
$.each(changedCountries, function () {
var itemCreateInfo = new SP.ListItemCreationInformation();
var newListItem = list.addItem(itemCreateInfo);
newListItem.set_item("CountryName", this.CountryName);
newListItem.set_item("StateName", this.StateName);
newListItem.update();
context.load(newListItem);
context.executeQueryAsync(ItemAdded, Failed);
});
}
function ItemAdded() {
//give a success message
$("#success").text("Item Added");
$("#success").show();
}
//function which apply KO bindings and make a call to SP using CSOM
function LoadData() {
completeCountryList = new CountryListViewModel();
GetList();
ko.applyBindings(completeCountryList);
}
function GetList() {
context = new SP.ClientContext(appWebUrl);
//No need to use SP.RequestExecutor.js for cross domain calls to host web in SP Hosted web
/* var factory = new SP.ProxyWebRequestExecutorFactory(appWebUrl);
context.set_webRequestExecutorFactory(factory); */
var hostContext = new SP.AppContextSite(context, hostWebUrl);
list = hostContext.get_web().get_lists().getByTitle("KnockoutList");
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml("<View><RowLimit>20</RowLimit></View>");
listItems = list.getItems(camlQuery);
context.load(listItems, "Include(Id, CountryName, StateName)");
context.executeQueryAsync(ListItemsLoaded, Failed);
}
function ListItemsLoaded(sender, args) {
var enumerator = listItems.getEnumerator();
while (enumerator.moveNext()) {
var currentItem = enumerator.get_current();
completeCountryList.AddCountries(currentItem.get_item("CountryName"), currentItem.get_item("StateName"), false);
}
}
function Failed(sender, args) {
alert(args.get_message());
}
function QS(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
<div id="divCountryList">
<h2>Country List</h2>
<br />
<table id="tblCountryList" border="1" class="tableStyle">
<thead>
<tr>
<th>Country</th>
<th>State</th>
</tr>
</thead>
<!-- Iterating through every list item using foreach of KO -->
<tbody data-bind="foreach: Countries">
<tr>
<td><input data-bind="value: CountryName" /></td>
<td><input data-bind="value: StateName" /></td>
</tr>
</tbody>
</table>
<br />
<button data-bind="click: AddCountries.bind($data, '', '', true)">Add State</button>
<button data-bind="click: UpdateSPList">Submit to SharePoint</button>
<br />
<div id="success" class="messages"></div>
<br />
<div id="failure" class="messages"></div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment