Search code examples
javascriptjquerybackbone.jsrequirejsunderscore.js

Dependencies in RequireJS with Backbone, Underscore, and jQuery in 2014


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?


Solution

  • 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