using unobtrusive namespace


/ Published in: JavaScript
Save to your folder(s)

Unobtrusive JavaScript should add as little as possible to the global object or global namespace of the environment in which it runs.
With following solution each module-writer's code is contained in private or in a unique namespace and cannot interfere with or intrude upon any other code at any time.


Copy this code and paste it in your HTML
  1. // creating 'namespace' - using domain name, reversed, as a single global name, e.g. example.com:
  2.  
  3. var org;
  4. if (!org)
  5. org = {};
  6. else if (typeof org != "object")
  7. throw new Error ("org already exists and is not an object");
  8. if (!org.example)
  9. org.example = {};
  10. else if (typeof org.example != "object")
  11. throw new Error ("org.example already exists and is not an object");
  12.  
  13.  
  14. // creating object inside namespace:
  15.  
  16. org.example.Highlight = function() {
  17. // define private data and functions
  18. var highlightId = "x";
  19. function setHighlight(color) {
  20. document.getElementById(highlightId).style.color = color;
  21. }
  22.  
  23. // return public pointers to functions or properties
  24. // that are to be public
  25. return {
  26. goGreen: function() { setHighlight("green"); },
  27. goBlue : function() { setHighlight("blue"); }
  28. }
  29. }(); //end closure definition and invoke it
  30.  
  31. //From any other module, these public methods could be invoked in either way as follows:
  32.  
  33. org.example.Highlight.goBlue();
  34.  
  35. var h = org.example.Highlight;
  36. h.goGreen();

URL: http://en.wikipedia.org/wiki/Unobtrusive_JavaScript

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.