Skip to content

AMD support #289

@haegrr

Description

@haegrr

I've started implementing AMD support in enchant and its plugins. The goal is of course to support loading enchant as a fully compliant module, while retaining full compatibility with traditional loading. This has required me to:

  1. Rewrite code that modifies global scope (very few changes).
  2. Wrap enchant, plugins and all non-AMD dependencies in conditional module definitions.
  3. Adapt plugins to be AMD-compliant (in a non-breaking way).

Step 3 presents a challenge (without breaking things, that is), because some plugins:

  1. have optional dependencies (a scenario not supported in AMD by design) on other plugins, like enchant.nineleap.
  2. modify enchant in various other places (e.g. adding new properties to enchant.Event) when loaded.

The first point is a real problem because there is no way such code can exist in an AMD module without loading those dependencies globally first. Of course, if the dependency is a plugin that also requires enchant to be loaded before it, the purpose of using AMD is lost. For this to work, I propose that code like this be implemented like the following example (simplified):

/* gl-nineleap.enchant.js (AMD use only) */
define(['enchant/nineleap', 'enchant/gl-core'], function(nineleap, glcore) {
  return glcore(nineleap);
});

/* gl.enchant.js (for both AMD and traditional loading) */
(function(factory) {
  if (typeof define === 'function' && define.amd) {
    define('enchant/gl-core', ['enchant'], factory);
    define(['enchant', 'enchant/gl-core'], function(enchant, glcore) {
      return glcore(enchant);
    });
  } else {
    enchant.gl = factory(window.enchant)(window.enchant.nineleap || window.enchant);
  }
})(function(enchant) {

  return function(parentModule) {
    var gl = {};
    gl.Core = enchant.Class.create(parentModule.Core, { /* ... */
    return gl;
  };
});

Work in progress can be seen in my amd-support branch. The conditional module definition wrappers have increased indentation levels by 1, so the GitHub diffs look bigger than they actually are. You might instead want to view the changes locally by running

git diff --ignore-space-change 88ecd9c HEAD

Please let me know what you think.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions