Search code examples
jquerybackbone.jsrequirejsunderscore.js

Backbone.js + underscore.js + jQuery in requireJS... is this the right way?


I'm trying to learning more about requireJS. So, if i understand it correctly, thw following code should be legit. Is this the right way to make my application modular?

This is application.js, where data-main attribute points:

requirejs.config({
    baseUrl: 'scripts/vendor', // By default, load all from vendor folder
    shim: {
        'backbone' : { // Do not support module loading
            deps: ['underscore', 'jquery'], // Do not support module loading
            exports: 'Backbone' 
        },
    },
    paths: {
        models: '../application/models', // Load from this folder if starts with user
        views: '../application/views',   // As above...
    }
});

requirejs(['jquery', 'backbone', 'views/user'], function($, Backbone, UserView) {
});

And my module for a view/model (pretty useless right now):

File application/views/user.js:

// underscore should be loaded now
define(['jquery', 'backbone', 'models/user'], function($, Backbone, User) { 
    return Backbone.View.extend({
        model: User,

        el: $('tr'),    

        initialize: function() {}
    });
});

File application/models/user.js:

define(['backbone'], function(Backbone) { // underscore should be loaded now
    return Backbone.Model.extend({
    });
});

Solution

  • You need to shim underscore as well since it's not AMD compatible.

     underscore: {
      exports: '_'
    }
    

    I'd recommend looking into https://github.com/tbranyen/backbone-boilerplate/ as it takes a lot of the headache out of using RequireJS.