2

I understand how things like proper name-spacing and the Module Pattern help issues associated with leaking into the global-scope.

I also completely see the value of resource dependency-management provided for in the require() protocol outlined in the CommonJS Specification.

However, I am befuddled as to the benefit of the AMD define() function's use and purpose.

The CommonJS signature for define is:

define(id?, dependencies?, factory);

Additionally…

At first, it "seemed" like yet-another plug-in wrapper...until I began to see folks use it alongside the Module Pattern.

So My Questions Are:

  • What does the define() protocol outlined in CommonJS specification buy me?
  • Is it somehow more eloquent?
  • Is it meant to replace the Modular Pattern?
  • Is it somehow faster?
  • If so, why?
Community
  • 1
  • 1
Prisoner ZERO
  • 13,848
  • 21
  • 92
  • 137

1 Answers1

2
// main.js
require("foo.js", function(foo) {
    console.log(foo === 42); // true
});

//foo.js

/*
define(42);

define({
   "foo": "bar"
});

define(["bar.js"], function(bar) {
    return bar.foo;
});
*/

define(function() {
     return 42;
});

Define is a great way to pass modular objects back without relying on global scope.

The particular API of define varies from library to library though.

Here the basic idea is that you call define in a file to define what that module is. Then when you require the file you get the module. This cuts out the middle man that is global scope.

It's no faster though (It's slower then injecting into global scope).

Using require and define you only have two global values.

The particular define example above matches the requireJS API

Raynos
  • 166,823
  • 56
  • 351
  • 396
  • So...every object is appended into the global-define object for you? – Prisoner ZERO May 19 '11 at 18:45
  • @PrisonerZERO not appended. Your simply calling `define`. Define will then pass it back through your `require` callback. These objects are not stored anywhere, it's just message passing. They are cached somewhere internally though. But not publically available. – Raynos May 19 '11 at 18:47
  • Since it isn't stored anywhere...I'm guessing you should use this pattern ONLY when it isn't a persistent object & you want to run once. – Prisoner ZERO May 23 '11 at 12:36
  • @PrizonerZERO all objects should not be stored anywhere. Have to objects bind to Pubsub systems, eventemitters, events on the DOM, etc. You don't need global state, you just need an object to react to state changes through event based messages rather then direct messages through a global object. – Raynos May 23 '11 at 13:24