Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 14th, 2012  |  syntax: None  |  size: 1.41 KB  |  hits: 15  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How do I create a namespace in JavaScript?
  2. MyNamespace.variable1
  3.        
  4. var Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'locale': {} };
  5.  
  6. Drupal.attachBehaviors = function (context, settings) {
  7.   context = context || document;
  8.   settings = settings || Drupal.settings;
  9.   // Execute all of them.
  10.   $.each(Drupal.behaviors, function () {
  11.     if ($.isFunction(this.attach)) {
  12.       this.attach(context, settings);
  13.     }
  14.   });
  15. };
  16.  
  17. Drupal.detachBehaviors = function (context, settings, trigger) {
  18.   context = context || document;
  19.   settings = settings || Drupal.settings;
  20.   trigger = trigger || 'unload';
  21.   // Execute all of them.
  22.   $.each(Drupal.behaviors, function () {
  23.     if ($.isFunction(this.detach)) {
  24.       this.detach(context, settings, trigger);
  25.     }
  26.   });
  27. };
  28.  
  29. // …
  30.        
  31. var MyNamespace = {};
  32. MyNamespace.variable1 = value1;
  33.        
  34. var MyNamespace = {};
  35. MyNamespace.variable1 = ...
  36.        
  37. // if Modules is null, create a new object, else use the currently defined instance
  38. var Modules = Modules || {};
  39.  
  40. Modules.A = {};
  41.  
  42. // sample instance variable
  43. Modules.A.instanceVar;
  44.  
  45. // sample function
  46. Modules.A.myFunc = function(param1, param2) {
  47.    // do something
  48. }
  49.        
  50. // if Modules is null, create a new object, else use the currently defined instance
  51. var Modules = Modules || {};
  52.  
  53. Modules.B = {};
  54.  
  55. // sample instance variable
  56. Modules.B.instanceVar;
  57.  
  58. // sample function
  59. Modules.B.myFunc = function(param1, param2) {
  60.    // do something
  61. }