Reputation: 48899
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({
});
});
Upvotes: 1
Views: 2936
Reputation: 8992
Use lodash instead underscore, is a superior full compatible solution and support AMD load. Check benchmarks and documentation ;)
requirejs.config({
appDir: ".",
baseUrl: "js",
paths: {
'jquery': ['//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min','libs/jquery-min'],
'lodash': 'libs/lodash.min',
'backbone': 'libs/backbone.min',
},
shim: {
'backbone': {deps:['lodash','jquery'], exports: 'Backbone'}
}
});
require([
'jquery', 'lodash','backbone'
],
function($, _){
return {};
});
Upvotes: 1
Reputation: 8577
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.
Upvotes: 5