Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to isolate my javascript code to prevent collisions?

Tags:

javascript

I have been writing a lot of javascript functions and event listeners and I want to move them into their own namespaced, isolated place that doesn't conflict when I concatenate and minify it with my other javascript files.

I am still new to javascript, so there may be simple solution to this answer. I started by creating a javascript object:

var MySpecialStuff = {
    init: function(){
        //do everything here
    }
};

Then in my html, on the page I want to use it on I can initialize this code:

<script>
    MySpecialStuff.init();
</script>

But then the init method started growing and I need to start breaking that code into smaller chunks, but I am stuck on the syntax and how to set private methods/variables and call them from within the init method and other private methods. How can I do this?

Am I headed in the right direction? What other ways can I / should I go about doing this sort of thing?

like image 864
Andrew Avatar asked Aug 05 '11 20:08

Andrew


1 Answers

You are headed in the right direction. You can use the module pattern to create an object with private members and methods like this:

var foo = function(){
  var bar = ""; //private

  function funk(){
    //private function    
    return "stuff";
  }

  return{
    getBar: function(){
      return bar;
    },
    init: function(){
      alert(funk());
    },
    randomMember: 0 //public member
  }


}();

Only what's in the return block is public, but you can call any private methods/access any private methods from within the return block.

like image 102
rav Avatar answered Nov 10 '22 09:11

rav