RequireJS – AMD Modules


RequireJS – AMD Modules


”;


A module in RequireJS is a scoped object and is not available in the global namespace. Hence, global namespace will not be polluted. RequireJS syntax allows to load modules faster without worrying about keeping track of the order of dependencies. You can load multiple versions of the same module in the same page.

Defining Modules

Module is defined using the define() function; the same function is used for loading the module as well.

Simple Name/Value Pairs

If the module is just a collection of name and value pairs, then you can use the following syntax −

define({
   state: "karnataka",
   city: "bangalore"
});

Defining Functions

A module can also use a function for frameworks, without having dependencies. This can be done by using the following syntax −

define(function () {
   
   //Do setup work here
   return {
      state: "karnataka",
      city: "bangalore"
   }
});

Defining Functions with Dependencies

If the module is having dependencies, the placement of the first argument (array of dependency names), the second argument (defining function) and the return object that defines the module is shown in the following syntax −

define(["./mnc", "./startup"], 
   function(mnc, startup) {
        
      return {
         state: "karnataka",
         city: "bangalore",
      
         addCompany: function() {
            mnc.decrement(this);
            startup.add(this);
         }
      
      }
   }
);

Defining a Module as a Function

It is not mandatory for a module to return only objects, any valid value from a function can also be returned. The following syntax is used to define a module as a function −

define(["./mnc", "./startup"],
   function(mnc, startup) {
       
      return function(title) {
         return title ? (window.title = title) :
         startup.storeName + '' '' + mnc.name;
      }
      
   }
);

Defining a Module with a Name

In some cases you may have to include a name for the module as the first argument to define(). This can be done by using the following syntax −

define("js2/title",
   ["js1/mnc", "js1/startup"],
   
   function(mnc, startup) {
      //Define js2/title object in here.
   }
   
);

Module Loading

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *