blog.scoreman.net

Aggregating tasks using SharePoint Search JavaScript Object Model

This is a follow up post on my previous post where I showed how you could use search and REST to aggregate a user’s tasks. This example will show the same thing except I use the JavaScript Client Object Model. The example is written as a SharePoint-hosted app using Visual Studio 2012 Update 3.

For this example to Work you will have to add a reference to sp.search.js like below or you could use Script on Demand to load it JavaScript code.

<script type="text/javascript" src="/_layouts/15/sp.search.js"></script>

For simplicity all error handling has been removed from the example code. Here is how the code in App.js looks like:

'use strict';

var context = SP.ClientContext.get_current();

$(document).ready(function () {
    getCurrentUserDisplayName().then(getUserTasks).then(displayResult);
});

function getCurrentUserDisplayName() {
    var deferred = jQuery.Deferred();
    var user = context.get_web().get_currentUser();

    context.load(user);
    context.executeQueryAsync(function () { deferred.resolve(user); });

    return deferred.promise();
}

function getUserTasks(user) {
    var deferred = jQuery.Deferred();
    var currentUserDisplayName = user.get_title();

    var keywordQuery = new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(context);
    keywordQuery.set_queryText("ContentTypeId:0x0108* NOT Status:Completed AND AssignedTo:" + currentUserDisplayName);
    keywordQuery.set
    var searchExecutor = new Microsoft.SharePoint.Client.Search.Query.SearchExecutor(context);
    var results = searchExecutor.executeQuery(keywordQuery);

    context.executeQueryAsync(function () { deferred.resolve(results); });

    return deferred.promise();
}

function displayResult(results) {
    var viewModel = function () {
        var self = this;
        self.tasks = ko.observableArray();

        jQuery.each(results.m_value.ResultTables[0].ResultRows, function () {
            self.tasks.push({
                title: ko.observable(this.Title),
                url: ko.observable(this.Path)
            });
        });
    };

    ko.applyBindings(new viewModel());
}

Leave a Reply