Wednesday, January 9, 2013

Namespaces with Javascript

When you are using javascript libraries, it gets messy because you can have multiple libraries of js functions, but some of the method names you are using may be shared by multiple libraries. Which method should it use? Use namespaces to clear that up. In .Net you have the namespace declaration; this is how it is done in javascript:

 The following is a simple page in Javascript:
The yellow text is the Namespace, the green text is the methods.

<html>
       <body onload="load()">
              <label id="lblMainText">label</label>
       </body>
 </html>

<script>
function load()
{
  var dataValue = MyNameSpace.getUrlVars()["data"];
  dataValue = MyNameSpace.replaceData(dataValue);
    document.getElementById('lblMainText').innerHTML = dataValue;
}

MyNameSpace =

{
     getUrlVars : function()
        {
         var vars = [], hash;
         var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
         for (var i = 0; i < hashes.length; i++) {
             hash = hashes[i].split('=');
             vars.push(hash[0]);
             vars[hash[0]] = hash[1];
         }
         return vars;
     },

   isEmpty : function(val)
   {
      if(val)
      {
         return ((val===null) || val.length==0 || /^\s+$/.test(val));
      }
      else
      {
         return true;
      }
   },

replaceData : function(s)
   {
      var arr1 =new Array('%20','%21','%40','%23','%24','%25','%5e','%26','%2a','%28','%29','%2b','%3d','%2c','%3c','%3e','%2f','%3f','%5b','%5d','%7b','%7d','%3a');
      var arr2 =new Array(' ','!','@','#','$','%','^','&','*','(',')','+','=',',','<','>','/','?','[',']','{','}',':');
      if(this.isEmpty(s)) return "";
      var re;
      for(var x=0,i=arr1.length;x<i;x++)
      {
         re = new RegExp(arr1[x], 'g');
         s = s.replace(re,arr2[x]); //swap arr1 item with matching item from arr2  
      }
      return s;
   }
}
</script>

No comments:

Post a Comment