Reputation: 163
I use RequireJS with Backbone.js.
In index.html I link require.js and define entry point start.js:
<script src="/app/vendor/require.js" data-main="/app/start"></script>
In start.js I configure RequireJS to access Backbone library with its dependencies:
require.config({
paths: {
jquery: 'vendor/jquery',
underscore: 'vendor/underscore',
backbone: 'vendor/backbone'
},
});
To use Backbone module in this file I can define it as a dependency:
require(['backbone'], function (Backbone) {
console.log(Backbone);
});
But I define as dependancy child module which has Backbone as its dependancy
start.js:
require.config({
paths: {
jquery: 'vendor/jquery',
underscore: 'vendor/underscore',
backbone: 'vendor/backbone'
},
});
require(['child'], function (Child) {
console.log(Backbone);
});
child.js:
define(['backbone'], function (Backbone) {});
Why I can access Backbone module in start.js without defining it? If I will use any other custom module I will receive error. This works only with Backbone module.
Upvotes: 0
Views: 247
Reputation: 151380
Your require
calls requires your child
module, which requires backbone
, so by the time child
is loaded and the callback executes, the backbone
module has been loaded. Now, let's see what this module does:
if (typeof define === 'function' && define.amd) {
define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
// Export global even in AMD case in case this script is loaded with
// others that may still expect a global Backbone.
root.Backbone = factory(root, exports, _, $);
});
...
As you can see there, even if you load Backbone as an AMD module, it still exports into the global space the symbol Backbone
. (The root
variable is equivalent to window
in a browser or global
in Node.js.) This is why your code works.
For my own work, I'd write the call like this:
require(['backbone', 'child'], function (Backbone, Child) {
so as to avoid relying on the global symbol. Future versions of Backbone could cease to export the global symbol when they detect that they are loaded as an AMD module.
Upvotes: 2