What is the proper way to load requirejs modules for models/views/collections in a backbone project?
I am using Yeoman to create a scaffolding for the app and am only starting to use require js.
My main.js file:
require.config({
paths: {
jquery: '../components/jquery/jquery',
underscore: '../components/underscore/underscore',
backbone: '../components/backbone/backbone',
bootstrap: 'vendor/bootstrap'
},
shim: {
underscore: {
exports: '_'
},
backbone: {
deps: ['jquery', 'underscore'],
exports: 'Backbone'
},
bootstrap: {
deps: ['jquery'],
exports: 'jquery'
}
}
});
define(['App', 'jquery', 'bootstrap'], function(App, $){
$(document).ready(function(){
App.start();
});
});
My scripts/App.js file:
define(['backbone'], function () {
App = {
init: function () {
// initialize router, views, data and layouts
},
start: function () {
App.init();
Backbone.history.start();
},
Views: {},
Models: {},
Collections: {},
Routers: {}
}
return App;
});
One of the models scripts/models/Gallery-model.js:
define(['App'], function(App){
var GalleryModel = Backbone.Model.extend({
initialize: function() {
this.items = new App.Collections.GalleryItemsCollection( this.get('children') );
}
});
App.Models.GalleryModel = GalleryModel;
return GalleryModel;
});
The other views, models, and collections are defined in a similar way. If I console.log(App)
, none of the Models, Views, or Containers methods are defined. Where should I be laoding all those modules in the code?
You cannot require App module because it wasn't shimmed. You also don't need to shim it because it is your code. Simply replace the define calls from:
to
or whatever is the correct path to that file (note that it should not include the .js at the end)