Singleton object in JavaScript

I developed a set of components that all read from the User Profile store. They are each designed to be independent, but are likely to be used together in a few variations. There is a risk that the number of calls to the REST endpoint for the profile gets hammered with all the requests. This is a perfect use case for the Singleton pattern in JavaScript.

I wrote a slightly different version from what is shown at that link. Instead of returning an object, I am returning a promise.

var sc = sc || {};

sc.UserProfile = (function () {  
  var profileLoaded;

  var getUserProfile = function () {
    var deferred = $.Deferred();

    var profileUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/sp.userprofiles.peoplemanager/getmyproperties";
    $.ajax({
      url: profileUrl,
      method: 'GET',
      headers: {
        "Accept": "application/json; odata=verbose"
      }
    })
    .success(function (data) {
      if (data) {
        deferred.resolve(data.d);
      } else {
        deferred.reject("No Results Found");
      }
    })
    .fail(function (data) {
      deferred.reject(data);
    });

    return deferred.promise();
  }

  return {
    GetUserProfile: function () {
      if (!profileLoaded) {
        profileLoaded = getUserProfile();
      }
      return profileLoaded.promise();
    }
  }
})();

With this code, each component can simply call the GetUserProfile() method:

sc.UserProfile.GetUserProfile().then(  
  // process...
);
comments powered by Disqus