0
votes

I have seen a lot of questions regarding using RequireJS w/ Backbone, Underscore, and jQuery. My question is slightly different; my app works, but I don't know why.

Currently, Underscore, jQuery, and Backbone all export AMD modules, so there is no need for me to shim them and export their variables anymore. Therefore, my main.js looks like the following code snippet.

main.js

require.config({
    paths: {
        jquery: 'lib/jquery/jquery-1.10.2',
        'jquery-ui': 'lib/jquery/jquery-ui-1.10.4.min',
        underscore: 'lib/underscore/underscore.min',
        backbone: 'lib/backbone/backbone.min',
        'backbone.localStorage': 'lib/backbone/backbone.localStorage'
    }
});

require(['jquery', 'jquery-ui', 'underscore', 'backbone', 'backbone.localStorage'], function() {

});

require.html

<!DOCTYPE html>
<html>
    <head>
        <title>My Sample Project</title>
        <!-- data-main attribute tells require.js to load
             scripts/main.js after require.js loads. -->
    </head>
    <body>
        <h1>My Sample Project</h1>
        <div id="test"> </div>
        <script type="text/javascript" data-main="js/main" src="js/lib/require/require.js"></script>
        <script type="text/javascript">

        </script>
    </body>
</html>

When I go to require.html, I can go to console and all my variables are there correctly loaded. For example, var x = Backbone.Model.extend({}); var y = new x; works just fine. However, Backbone depends on both Underscore and jQuery. Does RequireJS automatically resolve these dependencies using the modules supplied by these library, or is it only working as a fluke?

2
The libraries define their dependencies themselves. Have a look at the (uncompressed) code of Backbone or jQuery and search for define(, that should get you to the right line.christian314159

2 Answers

1
votes

You have require right after requirejs config setup

require(['jquery', 'jquery-ui', 'underscore', 'backbone', 'backbone.localStorage'], function() {

});

They loaded in the correct order by a chance, to control that sequence you need to define dependencies of each module in a shim

0
votes

Require helps a lot with this kind of work.

You can specify dependencies in a easy and correct way usim 'shim' command like this.

//Coffeescript example
paths:
    backbone : 'path/backbone'
    underscore : 'path/underscore'
    jquery: 'path/jquery'


 shim:
    backbone:
        deps:['underscore','jquery']
        exports: 'Backbone'

This way you define that when a module called 'Backbone' was called, require will load all the dependencies written inside deps:[]. Now it will never load backbone before underscore.

I have a blog and a post about it, unfortunately it's only in portuguese, but maybe helps.

http://www.rcarvalhojs.com/backbone/2014/06/03/comecando-require-backbone.html