Tuesday 8 August 2017

Add post render in custom methods - Sharepoint

Call post render events will help to render the html design after the page load event.
------------------------------------------------------------------
Create a new calback.js file for render functions:

function DW_AddPostRenderCallback(renderCtx, newCallback) {
    DW_AddRenderCallback(renderCtx, 'OnPostRender', newCallback, false);
}

function DW_AddRenderCallback(renderCtx, callbackType, newCallback, enforceUnique) {
    if (Boolean(renderCtx) && typeof newCallback == 'function' && callbackType != '') {
        var renderCallbacks = renderCtx[callbackType];

        if (renderCallbacks == null)
            renderCtx[callbackType] = newCallback;
        else if (typeof renderCallbacks == "function") {
            if (!Boolean(enforceUnique) || String(renderCallbacks) != String(newCallback)) {
                var array = [];

                array.push(renderCallbacks);
                array.push(newCallback);
                renderCtx[callbackType] = array;
            }
        }
        else if (typeof renderCallbacks == "object") {
            var exists = false;

            if (Boolean(enforceUnique)) {
                for (var i = 0; i < renderCallbacks.length; i++) {
                    if (renderCallbacks[i] == newCallback) {
                        exists = true;
                        break;
                    }
                }
            }
            if (!exists)
                renderCtx[callbackType].push(newCallback);
        }
    }
}

function DW_CallFunctionWithErrorHandling(fn, c, erv, execCtx) {
    if (DWClientRenderer.IsDebugMode(c)) {
        return fn();
    }
    try {
        return fn();
    }
    catch (e) {
        if (c.Errors == null)
            c.Errors = [];
        try {
            e.ExecutionContext = execCtx;
            if (Boolean(DWClientRenderer.AddCallStackInfoToErrors) && typeof execCtx == "object" && null != execCtx) {
                execCtx.CallStack = ULSGetCallstack(DW_CallFunctionWithErrorHandling.caller);
            }
        }
        catch (ignoreErr) { }
        c.Errors.push(e);
        return erv;
    }
}

DWClientRenderer = {
    GlobalDebugMode: false,
    AddCallStackInfoToErrors: false,
    RenderErrors: true
};
DWClientRenderer.IsDebugMode = function (renderCtx) {
    if (typeof renderCtx != "undefined" && null != renderCtx && typeof renderCtx.DebugMode != "undefined") {
        return Boolean(renderCtx.DebugMode);
    }
    else {
        return Boolean(DWClientRenderer.GlobalDebugMode);
    }
};

//function ULSSwq() {
//    var o = new Object;
//    o.ULSTeamName = "Microsoft SharePoint Foundation";
//    o.ULSFileName = "clientrenderer.commentedjs";
//    return o;
//}

var DWClientRenderer;

DWClientRenderer._ExecuteRenderCallbacks = function (renderCtx, callbackType) {
    var templateExecContext = {
        Operation: callbackType
    };
    var fn = function () {
        // ULSSwq();            ;
        return DWClientRenderer._ExecuteRenderCallbacksWorker(renderCtx, callbackType, templateExecContext);
    };

    return DW_CallFunctionWithErrorHandling(fn, renderCtx, null, templateExecContext);
};

DWClientRenderer._ExecuteRenderCallbacksWorker = function (renderCtx, callbackType, templateExecContext) {
    if (!renderCtx || callbackType == null || callbackType == '')
        return;
    var renderCallbacks = renderCtx[callbackType];

    if (renderCallbacks == null)
        return;
    if (typeof renderCallbacks == "function") {
        templateExecContext.TemplateFunction = renderCallbacks;
        renderCallbacks(renderCtx);
    }
    else if (typeof renderCallbacks == "object") {
        var numCallbacks = renderCallbacks.length;

        if (numCallbacks && typeof numCallbacks == "number") {
            for (var n = 0; n < Number(numCallbacks) ; n++) {
                if (typeof renderCallbacks[n] == "function") {
                    templateExecContext.TemplateFunction = renderCallbacks[n];
                    renderCallbacks[n](renderCtx);
                }
            }
        }
    }
};
---------------------------------------------------------------------------------------
Call in Document.ready function

$(document).ready(function () {
    var dw_NewsComments = new DigitalWorkplace.NewsHub.dwNewsComments();
    //if($('.comments-row').size() > 0)    {
      
    dw_NewsComments.GetNewsComments().then(function (dw_commentsCtx) {
        if (dw_commentsCtx !== null)
            DWClientRenderer._ExecuteRenderCallbacks(dw_commentsCtx, 'OnPostRender');
        });   
});

/* JS Methods for Callback Implementation
Make sure that these functions are not referred in any other files loading in the same page */
--------------------------------------------------------------------------------


Method Implementation:
 ---------------------------------------
// Add all the new items
                for (var i = 0; i < items.length; i++) {
                    currentObj.RenderComments(items[i], ctx);
                }
--------------------- -----------------------

RenderComments(item: any, ctx: any): void {

            var currentpage = _spPageContextInfo.pageItemId.toString();
            var currentuser = _spPageContextInfo.userId.toString();

            var thisTitle = item.ID;
            var updateBody = $(item.Body).text();
            var displayBody = updateBody.replace(/\n/g, '<br />');

            var checkDate = function (n) { return (Number(n) < 10) ? "0" + n : String(n); };
            var createdDate = new Date(item.Created);
            var delimiter = ".";
            var thisModDate = checkDate(createdDate.getDate()) + delimiter + checkDate(createdDate.getMonth() + 1) + delimiter + createdDate.getFullYear();
            //var thisModDate = jQuery.datepicker.formatDate('MM dd, yy', new Date(items[i].Created));
            //var thisModDate = "12-02-2017";
            var thisModDateHours = new Date(item.Created).getHours();
            var thisModDateMinutes = new Date(item.Created).getMinutes().toString();
            var ampm = 'AM';

            var authLogin = item.Author.Name;
            var authID = item.Author.ID;
            //var authLoginName = authLogin.substring(authLogin.indexOf('membership|') + 11);

            if (thisModDateHours > 12) {
                thisModDateHours = thisModDateHours - 12;
                var ampm = 'PM';
            }
            if (thisModDateMinutes.toString().length < 2) {
                thisModDateMinutes = '0' + thisModDateMinutes;
            }

            if (authID == currentuser) {
                if (item.CommentPageID == currentpage) {
                    $('.comment-list').append('<div class="comment-wrapper"><div authorName=' + authLogin + ' id=userInfo_' + thisTitle + '></div><div class="comment-author row">' +
                        '<div class="comment-tools" > <span id=commentSave_' + thisTitle + ' class="comment-save" style= "display:none">'+
                        '<a onclick= "DigitalWorkplace.NewsHub.dwNewsComments.prototype.UpdateNewsComments(&quot;' + thisTitle + '&quot;,&quot;#Update_Body' + thisTitle + '&quot;);" >' +
                        '<i class="glyphicon glyphicon-save" > </i></a> </span><span id=commentCancel_' + thisTitle + ' class="comment-cancel" style="display:none">' +
                        '<a onclick="DigitalWorkplace.NewsHub.dwNewsComments.prototype.CancelCommentButtons(&quot;' + thisTitle + '&quot;,this);return false;" href= "#"">' +
                        '<i class="glyphicon glyphicon-remove" > </i> </a> </span> <span id=commentEdit_' + thisTitle + ' class="comment- edit" >' +
                        '<a onclick="DigitalWorkplace.NewsHub.dwNewsComments.prototype.EditCommentButtons(&quot;' + thisTitle + ' &quot;,this); return false; " href= "#" >' +
                        '<i class="glyphicon glyphicon-edit"> </i> </a> </span> <span class="comment-delete" >'
                        + '<a onclick= "DigitalWorkplace.NewsHub.dwNewsComments.prototype.DeleteNewsComments(&quot;' + thisTitle + '&quot;);" >' +
                        '<i class="glyphicon glyphicon-trash"> </i> </a> </span> </div> <div id=commentUpdate_' + thisTitle + ' class="comment-update" style="display: none" >' +
                        '<textarea id="Update_Body' + thisTitle + '" rows= "4" > ' + updateBody + ' </textarea> </div > <div id=authorInfo_' + thisTitle + ' class="author-info" >' +
                        '<div class="author-name" > ' + item.Author.Title + ' </div> <div class="comment-time" > commented on ' + thisModDate + ' at ' + thisModDateHours + ':' +
                        thisModDateMinutes + ' ' + ampm + '</div > </div > </div> <div id=commentBody_' + thisTitle + ' class="comment-body" > ' + displayBody + ' </div> </div > ');
                }
            }
            else {
                if (item.CommentPageID == currentpage) {
                    $('.comment-list').append('<div class="comment-wrapper"><div authorName=' + authLogin + ' id=userInfo_' + thisTitle + '></div> <div class="comment-author row">' +
                        '<div id=authorInfo_' + thisTitle + ' class="author-info" > <div class="author-name" > ' + item.Author.Title + ' </div> <div class="comment-time">commented on ' + thisModDate +
                        ' at ' + thisModDateHours + ':' + thisModDateMinutes + ' ' + ampm + '</div></div></div> <div id=commentBody_' + thisTitle + ' class="comment-body" > ' + item.Body +
                        ' </div></div > ');
                }
            }
            var id = SP.Guid.newGuid().toString();
            var userPersonaId = 'userInfo_' + thisTitle;
            DW_AddPostRenderCallback(ctx, function () {
                var personaControlElement = document.getElementById(userPersonaId);
                if (personaControlElement === undefined || personaControlElement === null) {
                    return;
                }

                //Srch.U.ensureCSSClassNameExist(personaControlElement, "ms-srch-display-none");

                var executeOptions = {
                    url: _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v='" + authLogin + "'",
                    type: "GET",
                    dataType: "json",
                    headers: {
                        Accept: "application/json;odata=verbose"
                    }
                }

                $.ajax(executeOptions).then(function (data, textStatus, jqXHR) {
                    var result = data;
                    //user display name
                    var userDisplayName = result.d.DisplayName;
                    if (userDisplayName !== undefined && userDisplayName !== null && userDisplayName != '') {
                        var shortName = "";
                        var fullName = userDisplayName;
                        if (fullName !== "") {
                            if (fullName.indexOf(",") > -1) {
                                var idx = fullName.indexOf(",");
                                shortName = fullName.slice(0, idx);
                                var idx2 = fullName.indexOf(" ", idx + 2);
                                shortName += ", " + fullName.slice(idx + 2, idx2);
                            }
                            else {
                                shortName = fullName;
                            }
                        }
                        userDisplayName = shortName;
                    }
                    var userObj = result.d;
                    var userName = userObj.AccountName;
                    var userSiteUri = userObj.PersonalUrl;
                    //var userId = userObj.get_id();
                    var userPictureUri = userObj.PictureUrl;
                    var userEmailAddress = userObj.Email;
                    //Get user presence
                    var htmlStr = "";
                    if (userName !== undefined) {
                        if (userPictureUri == null || userPictureUri == "") {
                            var picsStr = '<span class="ms-imnSpan"><a href="#" onclick="IMNImageOnClick(event);return false;" class="ms-imnlink ms-spimn-presenceLink"><span class="ms-spimn-presenceWrapper ms-spimn-imgSize-8x72"><img onload="IMNRC(\'' + userEmailAddress + '\')" name="imnmark" title="' + userName + '" ShowOfflinePawn="1" class="ms-spimn-img ms-spimn-presence-disconnected-8x72x32" src="/_layouts/15/images/spimn.png?rev=23" alt="' + userName + '" sip="' + userEmailAddress + '" id="imn_' + id + ',type=sip" /></span></a></span></span><span class="ms-imnSpan"><a href="#" onclick="IMNImageOnClick(event);return false;" class="ms-imnlink" tabIndex="-1"><img onload="IMNRC(\'' + userEmailAddress + '\')" name="imnmark" title="T_' + userName + '" ShowOfflinePawn="1" class="ms-hide" src="/_layouts/15/images/spimn.png?rev=23" alt="' + userName + '" sip="' + userEmailAddress + '" id="simn_' + id + ',type=sip" /></a><span class="ms-peopleux-imgUserLink"><span class="ms-peopleux-userImgWrapper" style="width:72px; height:72px"><a href="' + userSiteUri + '"><div class="authorImg"><img src="/_layouts/15/images/PersonPlaceholder.200x150x32.png" alt="' + userName + '" /></div></a></span></span></span>';
                        } else {
                            var picsStr = '<span class="ms-imnSpan"><a href="#" onclick="IMNImageOnClick(event);return false;" class="ms-imnlink ms-spimn-presenceLink"><span class="ms-spimn-presenceWrapper ms-spimn-imgSize-8x72"><img onload="IMNRC(\'' + userEmailAddress + '\')" name="imnmark" title="' + userName + '" ShowOfflinePawn="1" class="ms-spimn-img ms-spimn-presence-disconnected-8x72x32" src="/_layouts/15/images/spimn.png?rev=23" alt="' + userName + '" sip="' + userEmailAddress + '" id="imn_' + id + ',type=sip" /></span></a></span></span><span class="ms-imnSpan"><a href="#" onclick="IMNImageOnClick(event);return false;" class="ms-imnlink" tabIndex="-1"><img onload="IMNRC(\'' + userEmailAddress + '\')" name="imnmark" title="T_' + userName + '" ShowOfflinePawn="1" class="ms-hide" src="/_layouts/15/images/spimn.png?rev=23" alt="' + userName + '" sip="' + userEmailAddress + '" id="simn_' + id + ',type=sip" /></a><span class="ms-peopleux-imgUserLink"><span class="ms-peopleux-userImgWrapper" style="width:72px; height:72px"><a href="' + userSiteUri + '"><div class="authorImg"><img src="' + userPictureUri + '" alt="' + userName + '" /></div></a></span></span></span>';
                        }
                        htmlStr += picsStr;

                        $('#' + userPersonaId).html(htmlStr);
                    }

                }, function (jqXHR, textStatus, errorThrown) {
                    console.log('error in fetching user properties' + errorThrown + jqXHR.responseText);
                    return null;
                });
            });
        }

----------------------------------------------------------------------






No comments:

Post a Comment