Reputation: 8278
I've spent last several hours trying to figure out why my code doesn't work as it's supposed to based on several tutorials I was trying to follow. Here's the thing. A lot of tutorials and articles out there on using Require.js with Backbone has code that looks something like this:
define(["jquery", "underscore", "backbone"], function($, _, Backbone){
return function(){
/* Some instantiation of Backbone stuff */
};
});
When I tried to run this code, the console would say "Backbone is undefined". Strange thing was that jQuery object was being successfully instantiated into $. It was just '_' and "Backbone" which were undefined. So I did some search and came across use.js
I am informed that use.js was born because the main contributor(s) of Backbone didn't want to change Backbone.js's code just to make it fit it into require.js, and I understand. So I tried using use.js to specify Backbone's dependency settings inside require's config like so:
require.config({
use: {
'backbone': {
'deps': ['use!underscore', 'jquery'],
'attach': 'Backbone'
},
'underscore': {
'attach': '_'
}
}
});
And after adding this code as well as calling 'use!backbone' from the original define instead of requiring 'underscore' and 'backbone', it finally works. But I don't understand what's happening here. If I have to go through all this work to make Backbone work, why do all those articles and tutorials out there don't mention this fact? It's almost like their version works fine without doing all this. Has something changed?
Also is this the only way to use require.js to deal with Backbone? Is there a simpler way? (Most up-to-date method)
Upvotes: 2
Views: 350
Reputation: 2469
do this
define('backbone', [], function(){ return window.Backbone;});
that way you have defined what backbone is and backbone will be attached to the window. Do this where you setup require initially. define backbone after initializing backbone.
define(["jquery", "underscore", "backbone"], function($, _, Backbone){
return function(){
/* Some instantiation of Backbone stuff */
};
});
hope that helps!
Cheers! Suj
Upvotes: 0
Reputation: 8179
Maybe this information will help you...
// This set's up the module paths for underscore and backbone
require.config({
'paths': {
"underscore": "libs/underscore-min",
"backbone": "libs/backbone-min"
},
'shim':
{
backbone: {
'deps': ['jquery', 'underscore'],
'exports': 'Backbone'
},
underscore: {
'exports': '_'
}
}
});
require([
'underscore',
'backbone',
'app'
],
function(_, Backbone, app){
app.init();
});
http://jcreamerlive.com/2012/07/14/using-backbonejs-and-amplifyjs-in-a-requirejs-2-0-application/
https://github.com/jcreamer898/RequireJS-Backbone-Starter
Upvotes: 1
Reputation: 14113
If you're using RequireJS 2.0, you can use the shim
functionality to include non-AMD modules.
The following article may help:
https://github.com/jrburke/requirejs/wiki/Upgrading-to-RequireJS-2.0#wiki-shim
Upvotes: 0