CHunky Universe of Vigourous Astonishing SHarepoint :)

Tag Archives: module

Paging with JSOM

If there are many list items you try retrieve with javascript object model,paging could be very useful. Today I came across a wonderful blog post series about javascript object model in SharePoint: The SharePoint javascript object model – Resources and Real World Examples posted by David Mann and published on Aptilon Blog.

There is an example how to achieve paging with JSOM. The key is items.get_listItemCollectionPosition() and query.set_listItemCollectionPosition()

I have refactored David’s example to avoid global variables and to put into a module. Here is it. If you have a Tasks list in your site with many items, just hit F12 to open the console and paste this and see the result:

(function(SP) {
      ctx = SP.ClientContext.get_current(),
      list = ctx.get_web().get_lists().getByTitle('Tasks'),
      view = '<View><ViewFields><FieldRef Name="Title"/></ViewFields><RowLimit>10</RowLimit></View>',
      query = new SP.CamlQuery(),
      init = function() {
      loadChunks = function() {
         items = list.getItems(query);
         ctx.executeQueryAsync(success, error);
      success = function() {
         console.log("\nFound Matching Items! ");
         enumerator = items.getEnumerator();
         while(enumerator.moveNext()) {
            console.log("Title: " + enumerator.get_current().get_item("Title") );
         position = items.get_listItemCollectionPosition();
         //when there are no items position is null
         position && loadChunks();
      error = function(sender, args) {
         console.log('Request failed. Error: ' + args.get_message() + '. StackTrace: ' + args.get_stackTrace());


javascript: Umbrella pattern

There are two great patterns for organizing javascript code: Prototype and Module pattern. More about them later in this post. But in reality I still see much of spagghetti Just an example: SharePoint 101 code samples. They are indeed very simple and isolated examples. And many projects use this simple way in mind when they begin. But when javascript code grows, it becomes a monster. Have you seen this biest? How is this monster created? Through good intentions (like everything else) in form of KISS mantra, to little time and the “commit and run”-behavior, or the worst: “I am c#-er, not Front-End-Developer”-spirit.

In this post I’ll introduce a kind of compromise the Umbrella pattern. But before that, let’s see how to recognize the spagghetti monster in javascript:

  • All are children of window. All global functions and variables are written directly, not encapsulated in some form. In the web browser all this stuff is appended to window. Variables like “index”, “query”, “selectedItem”, “onSuccess”, “onFail” are especially dangerous.
  • Conflicts arise between different functions with the same name. In javascript only the name matters. Eventhough parameters differ, they will be treated as the same function (where the last mentioned will override the previous functions). Try to add Gantt scheme view of a calendar webpart in SharePoint and a simple calendar webpart on the same page. One of them will stop working. Because both use moveToDate with different signatures and which do very diferrent things.
  • To avoid conflicts people create camel and Pascal monsters in the function names. Try to pronounce this: getTasksFromCurrentSiteTaskListWhichAreNotFinishedAndHaveBeenModifiedTheLastMonthForCurrentUserForTheProjectNewWave. Have you seen such function names. Leave some funny ones in comments 🙂

Now from negative to positive.

Umbrella pattern

The umbrella pattern is just a step from spagghetti towards better organization of javascript. So let’s take the spagghetti code and put it underneath namespaces, or call it umbrellas. It will protect from conflicts, give developers a better overview and traceability.

Umbrellas by Jethro Taylor (CC)

A little example from an imaginary company Takana:

//ensure that you don't override the main Umbrella (namespace)
var Takana = window.Takana || {};
//ensure that you don't override the sub-Umbrella Tasks
Takana.Tasks = Takana.Tasks || {};
Takana.Tasks.get = function() {
  //run SPServices, CSOM or jQuery ajax and listdata.svc
}; = function(tasks) {
  //use jQuery.tml, knockout.js, or just jQuery.each to render
Takana.Tasks.onSuccess = function(data) {
Takana.Tasks.onFail = function(xhr) {

It reminds most the module pattern, but gives a simpler way to create a module, and, I think, even simpler to refactor. If you need another umbrella, just feel free to create it, e.g. Takana.Notifications. Some other stuff which is not a business module can be shared like Takana.Utils umbrella.

The umbrella pattern gives you a better control of javascript, intellisense in Visual Studio and consoles in Firebug and Chrome Dev Tools. By the way. Do you want to know the contents of an umbrella? Just type Takana.Tasks in Chrome Dev Tools and see everything we have there:

Prototype and Module

Let’s recap these two patterns. They are really great and they have their own usage areas. The prototype pattern is more or less a workaround for missing the native object oriented programming api. So it is best to use when you have many objects which are very similar. An example from a “real life”:

var Pizza = function(name, bakeSpecial) { = name;
  this.bakeSpecial = bakeSpecial;
Pizza.prototype = {
  bake: function() {
    if (this.bakeSpecial) {
      console.log("Wow, I'll bake it in a special way");
    else {
      console.log("Bake. No problem. I'll do it");

Now we can create a collection of pizzas:

var pizzas = [ new Pizza("Margarita"),
               new Pizza("Quattro Staggione"),
               new Pizza("La Maffia", function() {
                   // bake in 12 mins instead and keep looking at left and right

Did you notice the flexible passing of a special bake instructions for “La Maffia”? Maybe like this one:

By UggBoy♥UggGirl [ PHOTO // WORLD // TRAVEL ] (CC)

Great. Now it is time for Module. The module pattern is a way to encapsulate, a way to simulate private and public “methods”. To keep our Pizza example, let’s create the Pizzeria:

var Pizzeria = function() {}();

The (); is the key action in the module pattern. This instantiates a defined “class”. So in the module pattern you define and then instatiate the object immediately. Therefore you can’t use it for multiple objects like pizzas.

Allright, our pizzeria shouldn’t be empty:

var Pizzeria = function() {
  //private "methods"
  var mixIngredients = function() {
    console.log("I am mixing ingredients");
  var makeDough = function() {
    console.log("I am making the dough");
  var giveToEat = function() {
    console.log("Ay, ay, hot, here is your pizza");

  //the object which will be instatiated
  var pizzeria = {
    //public "methods"
    makePizza: function(pizza){
      console.log("I'll fix your pizza: " +;
  return pizzeria;

The Pizzeria code creates one entry point: makePizza and hides all the “complicated” work behind the scenes:

To sum up, the prototype and module patterns give a better organization of javascript, hides complexity and helps to avoid repeating code. But if it is to difficult, tricky to trace, use my favourite: the Umbrella pattern which is a compromise between the “simple” spagghetti and and generic module pattern. The prototype can’t be “compromised”. It is actually a core technique in javascript: Date, String, Number and Pizza 🙂

Now let’s get some pizza :D:

var pizza = new Pizza("Hawaii");

javascript Module pattern

Want organize your js code in a kind of namespaces, or modules, then use the module pattern. I’ll take the dummy example for getting the current anchor. Let’s look how it would be if the prototype based approach is used:

var Contoso.Utils = function() {};
Contoso.Utils.prototype = {
  getCurrentAnchor: function() {
    var url = window.location;
    var anchor=url.hash; //anchor with the # character
    var anchor2=url.hash.substring(1); //anchor without the # character
    return anchor2;
var util = new Contoso.Utils();
var anchor = util.getCurrentAnchor();

The prototype pattern reminds the classic object oriented programming. Now, how would it look in the module pattern:

var Contoso = Contoso || {};
  Contoso.Utils = function() {
  var invokeCounter = 0;
  var logInvokeCounter = function() {
    console.log("invoked: " + invokeCounter + " times");
  return {
    getCurrentAnchor: function() {
      var url = window.location;
      var anchor=url.hash; //anchor with the # character
      var anchor2=url.hash.substring(1); //anchor without the # character
      return anchor2;
var anchor = Contoso.Utils.getCurrentAnchor();

It is like a static class in C# and java. It is instantiated only once (which can be a shortcoming sometimes). Pay attention to (); int the end of defition for Contoso.Utils, it ensures the instantiation of the Contoso.Utils.

var Contoso = Contoso || {}; checks if Contoso is not defined yet.

Another way to achieve this is to use ASP.NET Type.registerNamespase.

With Type.registerNamespace you can avoid overriding your classes:

Daniel Chronlund Cloud Tech Blog

News, tips and thoughts for Microsoft cloud fans

Вула Чăвашла

VulaCV - Чăвашла вулаттаракан сайт

Discovering SharePoint

And going crazy doing it

Bram de Jager - Architect, Speaker, Author

Microsoft 365, SharePoint and Azure

SharePoint Dragons

Nikander & Margriet on SharePoint

Mai Omar Desouki

PFE @ Microsoft

Cameron Dwyer

Office 365, SharePoint, Azure, OnePlace Solutions & Life's Other Little Wonders


Me and My doings!

Share SharePoint Points !

By Mohit Vashishtha

Jimmy Janlén "Den Scrummande Konsulten"

Erfarenheter, synpunkter och raljerande om Scrum från Jimmy Janlén

Aryan Nava

DevOps, Cloud and Blockchain Consultant


SharePoint for everyone


Ryan Dennis is a SharePoint Solution Architect with a passion for SharePoint and PowerShell

SharePoint 2020

The Vision for a Future of Clarity

Aharoni in Unicode

Treacle tarts for great justice

... And All That JS

JavaScript, Web Apps and SharePoint


Mostly what I know and share about...