Alexander Seredenko
Alexander Seredenko

Reputation: 819

Backbone.js and Require.js

I want to create Backbone.js app with Require.js. But I have an error in console: Uncaught Error: Module name "underscore" has not been loaded yet for context: _. Use require([])

require.config({
        baseUrl: 'js/',
        paths : {
            'jquery' : 'jquery',
            'underscore' : 'underscore',
            'backbone' : 'backbone',
            shim: {
                'underscore': {
                    exports: '_'
                },
                'backbone': {
                    deps: ['underscore', 'jquery'],
                    exports: 'Backbone'
                }

            }
        }
    });

    define('app', ['jquery','backbone', 'underscore'], function ($, Backbone, _){

        var Model = Backbone.model.extend({});
        var model = new Model;
    });

    require(['app','jquery', 'backbone', 'underscore']);

How I can resolve this problem?

Upvotes: 0

Views: 136

Answers (3)

Peter Wagener
Peter Wagener

Reputation: 2092

You still need to list underscore as a part of paths so you can refer to it in the shims. Also, not sure what your directory structure looks like, but I'm writing this with the assumption that library code is in the /js/libs directory). Finally, note you won't need to require any of the dependencies of app -- the joy of RequireJS is that it'll figure out what to load.

So...

require.config({
    baseUrl: 'js/',
    paths : {
        'jquery' : 'lib/jquery',
        'underscore' : 'lib/underscore',
        'backbone' : 'lib/backbone',
    },
    shim: {
        'underscore': {
            exports: '_'
        },
       'backbone': {
            deps: ['underscore', 'jquery'],
            exports: 'Backbone'
        }

    }
});

define('app', ['jquery','backbone', 'underscore'], function ($, Backbone, _){
    var Model = Backbone.Model.extend({});
    var model = new Model({
        foo: 'bar'
    });

    var app = {
        model: model
    };

    // ...

    return app;
});

require(['app'], function(App) {
    App.model.get('foo'); // <<=== returns 'bar'
});

Upvotes: 1

Kumaran
Kumaran

Reputation: 41

The shim is mentioned inside the paths object. I am not sure if that is the problem, but wanted to mention that here.

Upvotes: 1

Will
Will

Reputation: 544

You need Underscore.js as listed in your require statement.

Upvotes: -1

Related Questions