RequireJS - letronghieu4897/magento GitHub Wiki

RequireJS

RequireJS


Tree

RequireJS ___________________________________________________________
├── Concepts
|	├── 
|	└── 	
|
._____________________________________________________________________________________

1.Concepts

  • RequireJS is a module loade.
  • Following AMD (Asynchronous Module Defnition)

AMD

  • AMD API use 2 function
    • define ('module_id' , [dependencies] , function([param]) {};
      • module_id : Can null.
      • dependencies : ['ko' , '../template/renderer']; //Example
      • function([params]){} : function callback only run one time.
    • require (["main"], function(){});
      • main : array of modules need to load
      • function() : All modules loaded is passed into this function follow by order.
% ----------------- define example ----------------- %
//my/shirt.js now has some dependencies, a cart and inventory
//module in the same directory as shirt.js
define(["./cart", "./inventory"], function(cart, inventory) {
        //return an object to define the "my/shirt" module.
        return {
            color: "blue",
            size: "large",
            addToCart: function() {
                inventory.decrement(this);
                cart.add(this);
            }
        }
    }
);
% ----------------- require example ----------------- %

requirejs(["helper/util"], function(util) {
    //This function is called when scripts/helper/util.js is loaded.
    //If util.js calls define(), then this function is not fired until
    //util's dependencies have loaded, and the util argument will hold
    //the module value for "helper/util".
});

2.How to use it

 <script data-main="scripts/main.js" src="scripts/require.js"></script>

// data-main : data-main attribute tells require.js to load scripts/main.js after require.js loads

3.Example and Explain in Magento

<script type="text/javascript">
    require.config(
        {"baseUrl":"http://magento.example.com/static/adminhtml/Magento/backend/en_US"}
    );
</script>
⚠️ **GitHub.com Fallback** ⚠️