Dynamic namespace module template

Does anyone know what a template is for the ability to create a module template, but with the ability to set the namespace in which the module lives dynamically.

So, instead of what's below: -

var MODULE = (function () { 
  var my = {}, 
      privateVariable = 1; 

  function privateMethod() { 
      // ... 
  } 

  my.moduleProperty = 1; 
  my.moduleMethod = function () { 
      // ... 
  }; 

  return my; 
}());

The MODULE can be tuned to whatever you like, I remember how it was done on the screencast, but I don’t remember where ...

Basically, I would like to create a library that can be assigned to any namespace that the developer likes.

+3
source share
3 answers

I think you can simply add a method that allows you to set it and invalidate it MODULE.

http://jsfiddle.net/yrsdR/

my.namespace = function( ns ) {
    window[ns] = my;
    window.MODULE = null;
}

then

window.MODULE.namespace( "myNamespace" );

window.MODULE; // null
window.myNamespace // object

or you can return it to any desired variable.

http://jsfiddle.net/yrsdR/1/

my.namespace = function() {
    window.MODULE = null;
    return my;
}
window.myNamespace = MODULE.namespace();

window.MODULE; // null
window.myNamespace // object
0

, , . ( 1 ):

// ability to rename namespace easily
var AXS_NS = 'App';

window[AXS_NS] = (function (app, $, Modernizr) {

    app.config = {
        debug: false
    };

    app.init = function() {
        console.log('init');
    };

    return app;

})(window[AXS_NS] || {}, jQuery, Modernizr);

:

jQuery(function($){
    App.init();
});
0

, . javascript-. , script html.

-

<script src="js/myscript.js" namespaceName="myObject"><script>

myObject.hello() javascript.

javascript, .

/**
 * Dynamic mechanism for setting a javascript namespace.
 * 
 * This works by adding the namespaceName as an attribute to the script
 * element on your page.  Something like
 *
 *  **<script src="js/myscript.js" namespaceName="myObject"><script>**
 *
 * When the script has loaded it will have created a new javascript object
 * with the nemespace name "myObject".
 *
 * You can now use myObject.hello() which returns "ns.hello() called"<br/>
 * 
 * This works on later versions of chrome, firefox and ie.
 */
(function (ns) {
    ns.hello = function () {
        return "ns.hello() called";
    }
} (window[document.getElementsByTagName('script')[document.getElementsByTagName('script').length-1].attributes['namespaceName'].value]=
        window[document.getElementsByTagName('script')[document.getElementsByTagName('script').length-1].attributes['namespaceName'].value] || {}));

   [document.getElementsByTagName( 'script')   [Document.getElementsByTagName( 'script'). -1]   .attributes [ 'NamespaceName']. ] namespaceName script

0

Source: https://habr.com/ru/post/1791765/


All Articles