On Fri, Dec 21, 2012 at 6:29 PM, Alex Harui <aha...@adobe.com> wrote:

> I saw a brief overview of Require and it seemed way more difficult than
> goog.require, but I could be wrong about that.
>

Hi Alex,

using RequireJS may (only) become difficult if you use its advanced
features (e.g. path mappings), but my prototype *only* uses it as an
implementation of the AMD define() function, so all you really have to know
about it is this:

<mymodule>.js:

define(["<dependent module 1>", "<dependent module 2>", ..., "<dependent
module n>"],
  function(dependent_module_1, dependent_module_2, ..., dependent_module_n)
{
    // use dependent_module_1, dependent_module_2, ..., dependent_module_n
    return <value of mymodule>;
});

Then think module = class (or more precise "compilation unit").
In AMD/RequireJS, require(dependencies, callback) is like a define()
without defining a new module, i.e. without the callback function returning
anything.
The semantics is that when loading the application, each define/require
callback function of each (transitively) required module is executed
*exactly once*.

What may make this look a bit more complex / unfamiliar is that you have to
write down dependencies in two flavors: first, as a symbolic reference
(string), second, as the local variable that receives the value of this
reference. But the advantage is that the local variable allows much shorter
and more efficient access of the other module!

   require(["com.acme.my.very.nested.package.MyClass"], function(MyClass) {
     MyClass.doSomething();
   });


In contrast, using goog.require(), you only use one "name" for the
dependent module, as it converts the symbolic reference to a global
namespaced variable with the same name:

   goog.require("com.acme.my.very.nested.package.MyClass");
   com.acme.my.very.nested.package.MyClass.doSomething();

This nested global access is not very efficient, but during optimization,
GCC replaces it by a local variable much like the AMD style does it in the
first place.

To conclude, when running production code, there is not such a big
difference between CommonJS (Closure) and AMD (RequireJS) style. The
differences are the syntax (see above) and how dependencies are resolved
when running the debuggable, dynamically linked code. Syntactically,
CommonJS style might look a bit shorter and more familiar (although I don't
like the repeating fully qualified names), but running the dynamically
linked code in the browser has clear advantages in AMD style, as it is not
really possible to load modules synchronously in the browser (see
discussion in this thread).

Greetings
-Frank-

Reply via email to