Question

From the Logs, Backbone now registers itself for AMD (Require.js) Since v1.1.1.

Great, So I try to do the same for a module but there is something I don't understand.

If we look at section 4 of annotated sources the sources, The module doesn't return the global Backbone.

No need shim and window.Backbone is available. But How Backbone can not be undefined ?

// Definition Backbone Module

define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
   root.Backbone = factory(root, exports, _, $);
});

// Require Backbone module

require(['backbone'], function (Backbone) {
  Backbone // is not undefined ?
});

// Modal module Definition

define(['jquery'], function ($) {
   root.Modal = factory(root, {}, $);
});

// Require Modal module

require(['modal'], function (Modal) {
   Modal // undefined
});

Into my module (using the same structure), When I require my module, I got undefined if I don't return anything.

I have to return root.Modal in order to make it work. return root.Modal = factory(root, {}, $);

The main question is "How a module can be required while the module doesn't return anything ? "

I have missing something on requireJS, but I don't find it.

http://backbonejs.org/docs/backbone.html#section-4

Was it helpful?

Solution

The code in question is this:

define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
    root.Backbone = factory(root, exports, _, $);
});

Note now factory is called with exports as the 2nd parameter. The factory function is going to export Backbone's methods by setting fields on this object. This is why when you require Backbone, you get a useful value and not undefined or garbage.

This reason this works is that RequireJS supports defining a module by returning a value from the factory function you give to define, so you can do this:

define(function () {
    return {
        foo: function () { ... }
    };
});

But it supports also other means to do this, like for instance:

define(['exports'], function (exports) {
    exports.foo = function () { ... };
});

In the code above the module named exports in the list of dependencies is a special (and reserved) module name which means "give me an object on which I can set fields to export values". Backbone uses this 2nd way of exporting a value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top