JavaScript Encapsulation

I have been writing so much more JavaScript /jQuery the last couple of years with the boom of HTML5.

These newer Websites and Mobile Apps (Hybrid Apps) use JavaScript at the core. The Hybrid Apps are basically 100% code from JavaScript even the data layers and entities.

I have created jQuery plug-ins in the past, but more and more now I approach my code by encapsulating JavaScript.  This is required to create a good separation between all the JavaScript in modern apps to avoid any collisions. 

There are two approaches I have been using to create Classes in JavaScript to Encapsulate code. These "classes" in JavaScript can be setup as objects you instantiate or as static JavaScript classes. 

The following Screen Shot is a Test HTML Page to test calling JavaScript Objects and Named Function Expressions. (HTML File Attached)  Encapsulation.html (4.14 kb)

I. JavaScript Objects: Just like in C# or Java create an object from a JavaScript "Class". This way you can instantiate an instance of this class. 

var myUtil = new utilityObj();
var returnVal = myUtil.getMessage(testValue);

//------------------------------------------
// JavaScript Objects (Instantiated Class)
//------------------------------------------
function utilityObj() {
    var localValue;

    //-----------------------------	
    // Get Message Public
    //-----------------------------	
    this.getMessage = function(value)
    {			
	//set private value
	localValue = value;
        return getPrivateMessage();
    }

   //-----------------------------	
   // Get Message Private
   //-----------------------------	
    function getPrivateMessage()
    {
	return localValue;		
    }
}

 

II. JavaScript Named Functions: I like to think of these as "Static Classes" for JavaScript. You can call the functions in this class without instantiating an instance of the JavaScript class. 

utility.setMessage(testValue);

//---------------------------------------------
// Named Function Expressions (Static Class)
//---------------------------------------------
var utility = function () {
  var value = "Default Message";  

  function runPrivateFunc()
  {
     appendToDiv('runPrivateFunc()', '');
  }

  //Public Functions Here
  return  {     
  
    //-----------------------------
    //Set Message Function
   //-----------------------------	
   setMessage : function (val) {
	value = val;		
	appendToDiv('Exp Test A Set:', val);
    },
	
   //-----------------------------	
   //Get Message Function
   //-----------------------------	
    getMessage : function () {
       return value; 
    }
	
	
  }; // End Return  
}();   

 

 

HTML5 localStorage check for null or undefined

When saving values in localStorage those values are saved as string.  There are some guidelines when checking for undefined vs. null. 

Checking localStorage.variableName === undefined is the way to checked it.

Checking getItem("variableName") === null is the way to go.

Here is a sample and results in the console.

function testLocalStorage()
{
	console.log('TESTING localStorage.value1')
	if (localStorage.value1 === undefined) 
		console.log('localStorage.value1 - is undefined');

	if (localStorage.value1 === null) 
		console.log('localStorage.value1 - is null');
	
	console.log('\n');			
	console.log('TESTING getItem("value2")');

	var licValue = localStorage.getItem("value2");

	if(licValue === undefined) 
		console.log('getItem(localStorage.value2) - is undefined');

	if(licValue === null) 
		console.log('getItem(localStorage.value2) - is null');			 
}	

*** CONSOLE RESULTS ***

TESTING localStorage.value1
localStorage.value1 - is undefined

TESTING getItem("value2")
getItem(localStorage.value2) - is null

ASP.NET - Expire Cookie When User Closes the Browser

I had a need for Site A to communicate a value to Site B on the same domain. I wanted to do this through a cookie and if the user closed Site A the cookie would expire.  This can be done by not setting a expiration date on the cookie. 
//------------------------------------------------
// Site A - Create a cookie with no expiration  
//------------------------------------------------
private void SetCoookieValue()
{
  HttpContext CTX = HttpContext.Current;
  var CookieValue = 'TEST';
  
  var CookieName = "MY_COOKIE";
  HttpCookie MyCookie = new HttpCookie(CookieName);
  if (CTX.Request.Cookies[CookieName] != null) MyCookie = CTX.Request.Cookies[CookieName];
    
  MyCookie.Value = CTX.Server.UrlEncode(CookieValue);
    
  //No Expiration - it will expire when the user closes the browser
  //MyCookie.Expires = DateTime.Now.AddHours(8);
  CTX.Response.Cookies.Add(MyCookie);
}
    
//------------------------------------------------    
// Site B - Attempt to read the cookie in, 
// it should be gone after closing Site A
//------------------------------------------------  
private string GetCookieValue(string cookieName, string itemName)
{
    var CookieName = "MY_COOKIE";
    var CookieValue = string.empty;

    HttpCookie myCookie = Request.Cookies[CookieName];
    if (myCookie == null) return "No cookie found";

    //If you added a key vs. the value in the cookie
    //CookieValue = myCookie[itemName].ToString();

    //Get the value of the cookie 
    CookieValue = Page.Server.UrlDecode(myCookie.Value.ToString());
}