Friday, August 3, 2012

Modular JavaScript with RequireJs

"RequireJS is a JavaScript file and module loader"

While looking at some of the familiar namespacing patterns for JavaScript, I stumbled upon RequireJs.
Namespacing is essential in JavaScript to provide scope to your code in order to prevent conflicts with other variables, objects or functions with the same name that could have been loaded into the global namespace or scope.
There are no official namespaces in JavaScript but this can be achieved using objects and closures.


So why RequireJs?
  • Loads dependent scripts on demand
  • Explicit dependency referencing
  • No longer need to reference scripts manually in the correct order by dependency
  • Combine and bundle scripts using RequireJs optimizer
  • Loose coupling
  • Encapsulation
  • Dependency referencing (Refer to other modules)
How:

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

//This module has dependencies namely dependency1.js and dependency2.js
//in the same folder as this module
define(["./dependency1", "./dependency2"], function(dependency1, dependency2) {
    //return an object to define this module.
    return {
               property1: "value1",
               property2: "value2",
               property3: function() {
                   dependency1.foo();
                   dependency2.bar();
            }
        }
    }
);

Till next time...

1 comment:

  1. This is a cool library. Would love some more information about this, especially on ways to incorporate it in a ASP.NET MVC application.

    ReplyDelete