Namespacing in Javascript

So the other night I was working on some fancy script. It didn't work. After a bit of investigation, it turns out that one of the function names was already being used by a different function. Bummer. Of course this is why people use namespacing, to avoid problems such as this. So, here's how to write a sample bit of code to utilize namespacing in javascript:

 var myApp = (function(){
     var numericval = 10;

     return{
          moveLeft: function(){
               alert('left:'+numericval);
          },
          moveRight: function(){
               alert('right');
          }
     };
})();

$(document).ready(function(){
     $('.left').click(myApp.moveLeft);
});

Or to call it from other javascript code:

      myApp.moveLeft();



Related Posts


Simple Sticky Element

The user scrolls down the page and once the scrolling reaches the top of an element of my choosing, that element sticks to the top of the window, so it's always visible from that point on...
Read Post

Removing the Horizontal Margins on a Google Chart Graph

I seem to be able to successfully modify quite a bit with google charts, but I couldn't find a good way to remove the horizontal padding to the left and right of a google graph. From what I can find, there really isn't a good way to do it...
Read Post

PHP JSON Returned As Object Instead of Array

I was returning, what I thought was an array from PHP, but it kept returning it as a json object...
Read Post

A Simple Slideout Menu

I just wanted an easy slideout menu. Click on a link, and the menu slides out from the left side of the screen. Click on the link again, or somewhere else on the page, and the menu slides back in...
Read Post