Skip to content

Instantly share code, notes, and snippets.

@Salvodif
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Salvodif/c2c70b4189499c1c3230 to your computer and use it in GitHub Desktop.
Save Salvodif/c2c70b4189499c1c3230 to your computer and use it in GitHub Desktop.
Singleton with Deffered to use a cookie or get the info from an endpoint
ClientInfo = ( function ( ) {
// Instance stores a reference to the Singleton
var instance;
var obj = { };
function init ( currentUserRegion ) {
var publicMethods = {
getRegionalCurrency : function ( ) {
return obj.rcd;
},
getProjectView : function ( ) {
return obj.projectView === null ? "list" : obj.projectView;
},
setProjectView : function ( value ) {
obj.projectView = value;
},
Save : function ( ) {
SetCookie ( Constants.ContextCookieName, JSON.stringify ( obj ) );
}
};
var def = $.Deferred ( );
var cookie = GetCookie ( Constants.ContextCookieName );
var regionsURI = "/Regions?$filter=RegionName%20eq%20%27" + currentUserRegion + "%27&$select=ISOCurrencyCode";
if ( cookie === null || cookie === "" ) {
var endpointUrl = Context.GetInformationApiMethodUrl ( regionsURI );
Context.GetJSONFromDataHub (
endpointUrl,
function ( data ) {
obj.rcd = data.value [ 0 ].ISOCurrencyCode;
obj.projectView = "list"; // default
def.resolve ( publicMethods );
},
function ( err ) {
logger.Error ( "Error calling Information.svc", "Connections", "LoadPage", err );
def.reject ( "Error calling Information.svc" );
} );
} else {
obj = JSON.parse ( cookie );
def.resolve ( publicMethods );
}
return def;
}
return {
// Get the Singleton instance if one exists
// or create one if it doesn't
getInstance : function ( currentUserRegion ) {
if ( !instance ) {
instance = init ( currentUserRegion );
}
return instance;
}
};
} ) ( ClientInfo || { } );
$ ( document ).ready ( function ( ) {
// the plus "" is useful to don't get an error with plugins like resharper
var currentUserRegion = @Html.Raw( Json.Encode ( ViewBag.CurrentUserRegion ) ) + "";
var ctx = ClientInfo.getInstance ( currentUserRegion );
ctx.then ( function ( ci ) {
var currency = ci.getRegionalCurrency ( );
$ ( "#currency" ).text ( currency );
} );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment