INTERNET APPLICATION DEVELOPMENT
MID MARKET ERP DEVELOPMENT
by Derek Du
There are many documents regarding AMD and RequireJS out there. I just wanted to provide a way for people to start using RequireJS quickly and they can find the rest of the information later.
Firs,t let’s briefly talk about the problem we are trying to solve – say we have some code in a .js file that is referenced by a script tag in an HTML page and it defines a few variables and functions. All this stuff will be placed into the global variable set, which is very likely to cause naming conflicts when the project size gets bigger.
That’s why people invented Module Pattern to help encapsulate JS code and reduce the need for creation of global variables. A simple example:
In the example, we created an anonymous function block (i.e. anonymous closure) where we can create variables available locally to a global function, globalFunc. However this is still not optimal, because it defines a global variable within this block on which the code references it has no control.
Besides this global pollution issue, we also have a dependency issue. Using script tags to load scripts, we have to make sure dependencies are loaded in the correct order. For example, Backbone cannot be loaded before jQuery.
These are the 2 major issues I want to resolve using RequireJS. Now let’s start using RequireJS!
First download Require.js
Create a config file for RequrieJS for easy configuration
In your main html page, add just one script tag. Just specify the path of RequireJS and set the path of the config file in the data-main attribute. This allows RequireJS to find the config file and start your main.js script specified in the config file.
In your main.js file, define a module.
The example shows that RequireJS allows us to load a module in js code at the time we need it, and we have full control over the variable name assigned to it. Moreover, it automatically loads all the dependencies of the module before it is loaded.
Back to our config file, the setup for backbone and underscore is not complete, because they are non-AMD scripts. Simply put, they didn’t follow AMD standard to define themselves. For these modules, we need to add in the config file a shim configuration.
Now the configuration and the example are complete.
Note that there is another way to define your module. I prefer this approach just because it looks more straightforward. It is called CommonJS style definition.
There is much more about RequireJS and AMD in general that one can find. I recommend reading more from RequireJS’s site, but hopefully this gives you a general idea of modular programming and a starting point.
This post originally appeared in Derek's blog, Stuff. If you have any questions about this topic, please contact Derek.