I've read many answers and followed steps I could ( seems right to me) but still DevTools shows Backbone is not defined. error.
Here's how I use requirejs shim.
<script data-main="js/subject_main.js" src="js/libs/require.js"></script>
subject_main.js
require.config({
paths: {
bootstrap: '../libs/bootstrap.min',
jquery: '../libs/jquery',
underscore: '../libs/underscore',
backbone: '../libs/backbone',
text: '../libs/text',
json2: '../libs/json2',
templates: '../../templates'
},
shim: {
'boostrap':{
deps: ['jquery']
},
'backbone': {
deps: ['jquery', 'underscore'],
exports: 'Backbone'
},
'underscore': {
exports: '_'
}
}
});
require(['subjects', 'json2'], function(app) {
app.initialize();
});
subjects.js
define(['jquery', 'underscore', 'backbone', 'subject_router'], function($, _, Backbone, router) {
return {
initialize: function() {
Backbone.history.start();
}
};
});
subject_router
define([
'jquery',
'underscore',
'backbone',
'models/subject_item_model',
'collections/subjects_collection',
'views/subject_view'
],function($, _, Backbone) {
var AppRouter = Backbone.Router.extend({ ... });
return new AppRouter();
});
Chrome DevTools shows following sequence (order ) of scripts -
As you can see, backbone is loaded at very end. I don't know what's going wrong and where.
backbone.js or underscore.js look fine to me here, and indeed they are being loaded!
The 404s in your dev tool are referring to the source mapping files (underscore.min.map). You might want to look at this post: Missing Javascript ".map" file for Underscore.js when loading ASP.NET web page.
PS: In your subject_router code you have a mismatch on the arguments passed in to the module function.
Related
I was wondering how I could load backbone plugins with require.js I currently have this in my main.js
(function() {
'use strict';
require.config({
shim: {
underscore: {
exports: '_'
},
backbone: {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
deepModel: {
deps: ['underscore', 'backbone']
}
},
paths: {
jquery: 'lib/jquery/jquery',
underscore: 'lib/underscore/underscore',
backbone: 'lib/backbone/backbone',
text: 'lib/requirejs-text/text',
deepModel: 'lib/deep-model/deep-model.min'
},
In my model I have something like this
var myapp = myapp|| {};
(function() {
'use strict';
define([
'jquery',
'underscore',
'backbone',
'deepModel',
], function($, _, Backbone) {
myapp.model= new Backbone.DeepModel.extend({
defaults: {
},
urlRoot: '/users',
For some reason the above does not seem to work as expected. I think I am missing something but not sure what that is. I am using the backbone deep model plugin.
This is the error I get in the debugger
Uncaught TypeError: Object [object Object] has no method 'apply'
Add DeepModel to your scope in function signature:
define([
'jquery',
'underscore',
'backbone',
'deepModel',
], function($, _, Backbone, **DeepModel**)
It might make your life easier if you use the AMD-compatible version of backbone and underscore. By default, they do not support AMD.
https://github.com/amdjs/backbone
https://github.com/amdjs/underscore
I'm trying to get Masonry loaded into my app using RequireJS, but it keeps causing backbone to spit out a "object is not a function" error anytime I add it.
Edit: possibly related to this issue.
main.js
require.config({
paths: {
jquery: 'lib/jquery-1.9.1',
underscore: 'lib/underscore-1.5.2',
backbone: 'lib/backbone-1.0.0',
masonry: 'lib/masonry.pkgd'
},
shim: {
backbone: {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
underscore: {
exports: '_'
}
}
});
require(['app'], function(App){
App.initialize();
});
app.js
define([
'jquery',
'underscore',
'backbone',
'masonry',
'collections/ideas',
], function($, _, Backbone, Masonry, IdeasCollection) {
var IdeasView = Backbone.View.extend({
el: $('#container'),
initialize: function() {
...
},
render: function(){
...
}
});
return IdeasView;
});
To use Masonry as a jQuery plugin with RequireJS, you’ll need to run jQuery bridget.
Check the documentation:
http://masonry.desandro.com/appendix.html#requirejs
You can download bridget here:
https://github.com/desandro/jquery-bridget
Then you can include an run bridget and it should work fine
define([
'jquery'
, 'underscore'
, 'backbone'
, 'config'
, 'app'
, 'jquery.masonry'
, 'jquery.bridget'
], function ($, _, Backbone, Config, App, Masonry, bridget) {
initialize : function () {
bridget('masonry', Masonry);
}
});
Hope it helps!
This is one way you can run it without bridget:
requirejs-config.js:
var config = {
paths: {
"lib-masonry": "Module/js/lib/masonry.pkgd.min"
},
shim: {
"lib-masonry": {
deps: ['jquery', 'jquery/ui']
}
}
}
and then in another module where you want to use it:
define([
'jquery',
'lib-masonry'
], function ($, Masonry) {
$.widget('ModuleNamespace.containerMasonry', {
options: {
},
_create: function() {
var msnry = new Masonry('.grid', {
itemSelector: '.grid__item',
columnWidth: 200
});
// .. code
}
});
return $.ModuleNamespace.containerMasonry;
});
I'm newbie to backbone.js and require.js. Currently I create one backbone project.
Here is app.js code :
define([
'jquery',
'underscore',
'backbone',
'script',
'router'
], function($, _, Backbone, Script, Router){
var initialize = function(){
Router.initialize();
};
return {
initialize: initialize
};
});
Here is main.js:
require.config({
path: {
jquery: 'libs/jquery/jquery-min',
underscore: 'libs/underscore/underscore-min',
backbone: 'libs/backbone/backbone-min',
script: 'libs/scripts/index'
},
shim:{
backbone: ['jquery', 'underscore'],
script: ['jquery'],
enforceDefine: true
}
});
require([
'app',
], function(App){
App.initialize();
});
And the last one is router.js :
define([
'jquery',
'underscore',
'backbone',
'script'
], function($, _, Backbone){
var AppRouter = Backbone.Router.extend({
routes:{
'*actions': 'defaultAction'
}
});
var initialize = function(){
var app_router = new AppRouter;
app_router('route:defultAction', function(actions){
});
Backbone.history.start();
};
return {
initialize: initialize
};
});
I want to add jquery-json library to my project. If in html project, here is my code :
<script type="text/javascript" src="jquery-min.js"></script>
<script type="text/javascript" src="jquery.json-2.4.min.js">
</script>
<script>
function serializeObjToJSON(_obj) {
var _json = $.toJSON(_obj);
return _json;
}
function deserializeJSONToObj(_json) {
var _obj = $.evalJSON(_json);
return _obj;
}
</script>
I want to import the library above and using it in my backbone project. But I have no idea how to do that.
Any help would be much appreciated, thank you.
in your main JS you should add the JSON reference. (put jquery.json-2.4.min.js into lib/ folder)
require.config({
path: {
jquery: 'libs/jquery/jquery-min',
underscore: 'libs/underscore/underscore-min',
backbone: 'libs/backbone/backbone-min',
script: 'libs/scripts/index',
json: 'libs/jquery.json-2.4.min'
}
Then you can add it as a definition into the app.js or any other module.js file which is using it in reference .
define([
'jquery',
'underscore',
'backbone',
'script',
'router',
'json'
], function($, _, Backbone, Script, Router, Json){
//Code
}
Then within your js files you have your reference to json. You can call it by using
Json.method()
for example.. As soon as you write json, it looks for your definition and then reffers to that lib for the functions you called.
So your index.js or whichever end you want to call it will require something like :
define([
'jquery',
'underscore',
'backbone',
'script',
'router',
'json'
], function($, _, Backbone, Script, Router, Json){
serializeObjToJSON: function(_obj) {
var _json = Json.toJSON(_obj);
return _json;
}
deserializeJSONToObj: function(_jsonObject) {
var _returnObj = Json.evalJSON(_jsonObject);
return _returnObj;
}
I'm going a bit crazy here. I'm trying to use Grunt to go through a large RequireJS-based project and combine and minify the results during the deployment process. Here is my grunt process (using grunt-contrib-requirejs):
requirejs: {
compile: {
options: {
baseUrl: "public/js",
mainConfigFile: "public/js/config.js",
name: 'config',
out: "public/js/optimized/script.min.js",
preserveLicenseComments: false
}
}
}
Initially, I was taking the outputted script and placing it in the HTML -- but this lead to the 'define is undefined' error that means that RequireJS wasn't evoked. So instead, I'm putting in the HTML like this:
<script data-main="js/optimized/script.min" src="js/vendor/require.js"></script>
However, now I'm only getting a blank page.
The closest thing I can find out there that sounds like this is here, but's not being super helpful right now. For reference, I was using this as a starting point of my project -- however, when I run it, everything seems to be working for them but I can't find the differences.
Here is my config.js file:
require.config({
//Define the base url where our javascript files live
baseUrl: "js",
//Increase the timeout time so if the server is insanely slow the client won't burst
waitSeconds: 200,
//Set up paths to our libraries and plugins
paths: {
'jquery': 'vendor/jquery-2.0.3.min',
'underscore': 'vendor/underscore.min',
'backbone': 'vendor/backbone.min',
'marionette': 'vendor/backbone.marionette',
'mustache': 'vendor/mustache.min',
'bootstrap': 'vendor/bootstrap.min',
'bootbox': 'vendor/bootbox.min',
'jquery-ui': 'vendor/jquery-ui-1.10.2',
'app-ajax': '../conf/app-ajax',
'common': 'common',
'moment': 'vendor/moment.min'
},
//Set up shims for non-AMD style libaries
shim: {
'underscore': {
exports: '_'
},
'backbone': {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
'marionette': {
deps: ['backbone', 'underscore', 'jquery'],
exports: 'Marionette'
},
'mustache': {
exports: 'mustache'
},
'bootstrap': {
deps: ['jquery']
},
'bootbox': {
deps: ['jquery', 'bootstrap'],
exports: 'bootbox'
},
'jquery-ui': {
deps: ['jquery']
},
'jquery-layout': {
deps: ['jquery', 'jquery-ui']
}
}
});
//Initalize the App right after setting up the configuration
define([
'jquery',
'backbone',
'marionette',
'common',
'mustache',
'bootbox',
'controllers/GlobalController',
'routers/GlobalRouter'
],
function ($, Backbone, Marionette, Common, Mustache, bootbox) {
//Declare ECMAScript5 Strict Mode first and foremost
'use strict';
//Define the App Namespace before anything else
var App = Common.app_namespace || {};
//Create the Marionette Application
App.Application = new Marionette.Application();
//Add wrapper region, so we can easily swap all of our views in the controller in and out of this constant
App.Application.addRegions({
wrapper: '#wrapper'
});
// Set up Initalizer (this will run as soon as the app is started)
App.Application.addInitializer(function () {
//Reach into Marionette and switch out templating system to Mustache
Backbone.Marionette.TemplateCache.prototype.compileTemplate = function (rawTemplate) {
return Mustache.compile(rawTemplate);
};
var globalController = new App.Controllers.GlobalController();
var globalRouter = new App.Routers.GlobalRouter({
controller: globalController
});
//Start Backbone History
Backbone.history.start();
});
//Start Application
App.Application.start();
}
);
Okay, so this is the crazy simple fix:
In the module that's declared after the require.config, use 'require' instead of 'define' when declaring the module.
If you use 'define', it added 'config' as a dependency of that module, which broke the whole thing. Craziness!
I'm relatively new to Backbone and RequireJS, so please bear with me. I'm getting an error when I do the following in my collection: _.range(0,10). It's giving me this error:
Uncaught TypeError: Cannot call method 'range' of undefined
Somehow the "_" is not getting resolved when my Collection is loaded. Here's my collection below:
define([
'jquery',
'underscore',
'backbone',
'collections/feed',
'text!/static/templates/shared/display_item.html'
], function($, _, Backbone, FeedCollection, DisplayItem){
debugger; // Added this to test the value of _
var FeedView = Backbone.View.extend({
el: '#below-nav',
initialize: function () {
this.feedCollection = new FeedCollection();
},
feed_row: '<div class="feed-row row">',
feed_span8: '<div class="feed-column-wide span8">',
feed_span4: '<div class="feed-column span4">',
render: function () {
this.loadResults();
},
loadResults: function () {
var that = this;
// we are starting a new load of results so set isLoading to true
this.isLoading = true;
this.feedCollection.fetch({
success: function (articles) {
var display_items = [];
// This line below is the problem...._ is undefined
var index_list = _.range(0, articles.length, 3);
_.each(articles, function(article, index, list) {
if(_.contain(index_list, index)) {
var $feed_row = $(that.feed_row),
$feed_span8 = $(that.feed_span8),
$feed_span4 = $(that.feed_span4);
$feed_span8.append(_.template(DisplayItem, {article: articles[index]}));
$feed_span4.append(_.template(DisplayItem, {article: articles[index+1]}));
$feed_span4.append(_.template(DisplayItem, {article: articles[index+2]}));
$feed_row.append($feed_span8, $feed_span4);
$(that.el).append($feed_row);
}
});
}
});
}
});
return FeedView;
});
I added the debugger line so that I could test the values of all the arguments. Everything loaded fine, except for _. Could this be something wrong with my config.js file?
require.config({
// Set base url for paths to reference
baseUrl: 'static/js',
// Initialize the application with the main application file.
deps: ['main'],
paths: {
jquery: 'libs/jquery/jquery.min',
require: 'libs/require/require.min',
bootstrap: 'libs/bootstrap/bootstrap.min',
text: 'libs/plugins/text',
underscore: 'libs/underscore/underscore',
backbone: 'libs/backbone/backbone',
json: 'libs/json/json2',
base: 'libs/base/base'
},
shim: {
'backbone': {
// These script dependencies should be loaded first before loading
// backbone
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
'bootstrap': {
deps: ['jquery'],
exports: 'Bootstrap'
}
}
})
Your help is greatly appreciated. My head is spinning as a result of this error.
Based off the project that I'm working on, you need a shim for underscore as well. Underscore isn't 'exported' per say, so use this instead:
shim: {
'backbone': {
// These script dependencies should be loaded first before loading
// backbone
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
'bootstrap': {
deps: ['jquery'],
exports: 'Bootstrap'
},
'underscore': {
exports: '_'
}
}
Seems this might also be 'duplicate' question of Loading Backbone and Underscore using RequireJS - one or two of the answers down the list there is a mention of this setup.