Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save skokasik/7067622 to your computer and use it in GitHub Desktop.
Save skokasik/7067622 to your computer and use it in GitHub Desktop.
Javascript: Prototype Pattern (xmlencode, convert to ISO date, json object length, create object from sharepoint responseXML)
/* sample for prototype pattern, xmlencode, convertToISODate, get the length of a json object, create json object from sharepoint responseXML */
var Utilities = function() {
};
Utilities.prototype = {
xmlencode : function (string) {
//encode the special character to make sure the caml request works
return string.replace(/\&/g,'&'+'amp;').replace(/</g,'&'+'lt;').replace(/>/g,'&'+'gt;').replace(/\'/g,'&'+'apos;').replace(/\"/g,'&'+'quot;');
},
convertToISODate : function( date ) {
//sharepoint date field only accept ISODate format date should be javascript date format: mm/dd/yyyy
date = date || new Date();
function pad( n ) {
return n < 10 ? '0' + n : n;
}
return date.getFullYear() + '-' +
pad( date.getMonth() + 1 ) + '-' +
pad( date.getDate() ) + 'T' +
pad( date.getHours() ) + ':' +
pad( date.getMinutes() )+ ':' +
pad( date.getSeconds() )+ 'Z';
},
objLength : function(obj){
var key,len=0;
for(key in obj){
len += Number( obj.hasOwnProperty(key) );
}
return len;
},
createJsonObjects : function (responseXML, columnMapping)
{
var results = [];
var jsonObject = {};
responseXML.SPFilterNode("z:row").each(function (itemNum){
var $th = $(this);
jsonObject ={};
for (var prop in columnMapping) {
if (columnMapping.hasOwnProperty(prop) && $th.attr(columnMapping[prop]) !== undefined) {
if (prop.indexOf("Date") > 0)
{
var auDateFormat = $th.attr(columnMapping[prop]).replace( /(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1");
jsonObject[prop] = auDateFormat.substring(0,auDateFormat.indexOf(" ")+ 1);
}
else
{
jsonObject[prop] = $th.attr(columnMapping[prop]).indexOf("#") > 0 ? $th.attr(columnMapping[prop]).substring($th.attr(columnMapping[prop]).indexOf("#") + 1): $th.attr(columnMapping[prop]).replace(/\.0000.*/g, "");
}
}
}
results.push (jsonObject);
});
return results;
}, // end function
replaceHtmlControl : function(controlId, itemArray) {
//Replace the OPTIONS of an existing SELECT control
if (itemArray.length > 0) {
$("#" + controlId).find("option").remove();
}
$.each(itemArray, function(i, item){
$("#" + controlId).append($('<option>', {
"data-spID": item.ID,
value: encodeURIComponent(item.Title),
text : item.Title
}));
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment