I’m currently trying RequireJS 2.0 and consequently have to change some code.
Here’s my main.js, launched with data-main in my index.phtml.
EDIT : Forgot project structure, can be useful 🙂
->public
-> css
-> js
app.js
facade.js
main.js
router.js
...
-> collections
-> libs
-> backbone
-> jquery
-> json2
-> plugins
-> require
-> underscore
-> templates
...
// Filename: main.js
// Require.js allows us to configure shortcut alias
// There usage will become more apparent futher along in the tutorial.
require.config({
//Here baseUrl = /js (Loaded in data-main in logged.phtml)
// 3rd party script alias names (Easier to type "jquery" than "libs/jquery-1.7.2.min")
paths: {
jQuery: 'libs/jquery/jquery',
Underscore: 'libs/underscore/underscore',
Backbone: 'libs/backbone/backbone',
JSON: 'libs/json2/json2',
templates: '../templates'
},
// Sets the configuration for your third party scripts that are not AMD compatible
shim: {
'libs/plugins/bootstrap-min': ['jQuery'],
'libs/plugins/jquery.cookies.min': ['jQuery'],
'jQuery': {
exports: '$'
},
'JSON': {
exports: 'JSON'
},
'Underscore': {
exports: '_'
},
'Backbone': {
deps: ['Underscore', 'jQuery'],
exports: 'Backbone' // attaches "Backbone" to the window object
}
}
});
define([
// Load our app module and pass it to our definition function
'app',
'jQuery',
'Underscore',
'Backbone',
'JSON'
], function(App) {
// The "app" dependency is passed in as "App"
// Again, the other dependencies passed in are not "AMD" therefore don't pass a parameter to this function
App.initialize();
});
I tried to add ‘router’ to this file with its dependencies but nothing has changed, so I assumed it was useless.
And here’s the app.js loaded when calling App:
define([
'jQuery',
'Underscore',
'Backbone',
'JSON',
'router', // Request router.js
'i18n!nls/langs',
'facade',
//'order!libs/plugins/jquery.backstretch.min'
//'libs/plugins/backbone.validation.min'
], function($, _, Backbone, JSON, Router, langs, facade) {
var initialize = ...
...
...
return {
initialize: initialize
};
});
Here’s the problem, in my router.js definition, I used a console.log and it showed me that it was returning the right object.
But when I call router in my app.js, router stays undefined.
I probably made a mistake but I can’t find it.
EDIT : Added the router.js code
require([
'jQuery',
'Underscore',
'Backbone',
'JSON',
'facade',
'models/UserModel',
'libs/plugins/jquery.cookies.min'
], function($, _, Backbone, JSON, facade, User, cookies){
var AppRouter = Backbone.Router.extend({
...
});
var app_router = new AppRouter;
// Start Backbone history a neccesary step for bookmarkable URL's
Backbone.history.start();
return app_router;
});
Your
router.jsfile isn’t defining an AMD module properly. You need to usedefine, notrequire.