Backbone.js and Require.js issue - javascript

I am trying to convert an existing Backbone.js project into Require.js.
As recommended I am modularising my components. My router is the starting point in the application, thus my main.js require file looks like this:
requirejs.config({
'baseUrl': '/',
'paths': {
'app': 'app',
// define vendor paths
'jquery' : 'bower_components/jquery/jquery',
'underscore' : 'bower_components/underscore/underscore',
'backbone' : 'bower_components/backbone/backbone',
'handlebars' : 'bower_components/handlebars/handlebars',
'nprogress' : 'bower_components/nprogress/nprogress',
},
'shim':{
'jquery': {
'exports': '$'
},
'underscore': {
'exports': '_'
},
'backbone': {
'deps': ['jquery', 'underscore'],
'exports': 'Backbone'
},
'handlebars': {
'exports': 'Handlebars'
}
}
});
require(['app/js/routes/router'], function(Router) {
// Fire up the quattro
});
My router then looks like this
define(['backbone', '/app/js/views/HomepageView'], function(Backbone) {
var AppRouter = Backbone.Router.extend({
routes: {
"": "showHomepage",
"categories/:sofa": "showCategoryList",
"range/:categoryName/:sofaName": "showProductRange",
"customersearch/:customerName": "showCustomerSearch"
}
});
// Initialise our router
var router = new AppRouter;
router.on("route:showHomepage", function(param){
localStorage.removeItem('lastProduct');
var homepageview = new HomepageView({ el: $('#content') });
})
// Start the router
Backbone.history.start();
});
However when I navigate to my route '/' for HomepageView to initialise, I get the following error no matter what I try and I cannot seem to find the solution..
Uncaught ReferenceError: Backbone is not defined HomepageView.js:1

changing the first line to the following would be a start.
define(['backbone', '/app/js/views/HomepageView'], function(Backbone, HomePageView) {

Related

Marionettejs Routes

I'm new to Marionette and I just can't get routes to work.
I'm using Marionette's 2.4.1 version, and trying to do it the simplest way possible so it'll just work.
This code works for old version of Marionette, v1.0.2, which was included in one of the yeoman's generator. I know there's a huge gap between those two versoins but for every post, blog, official documentation and even books written for this framework code stays the same.
There are no errors in console, but the 'home' method just won't start.
Am I missing something here?
application.js (Application body):
define(['backbone', 'marionette'],
function (Backbone, Marionette) {
'use strict';
var App = new Marionette.Application();
App.Router = Marionette.AppRouter.extend({
appRoutes: {
"home": "home"
}
});
var myController = {
"home": function() {
console.log("This thing just won't work.");
}
};
/* Add initializers here */
App.addInitializer(function () {
console.log('App initialized');
new App.Router({
controller: myController
});
});
App.on("initialize:after", function () {
if (Backbone.history) {
Backbone.history.start();
}
});
return App;
});
main.js (Starts our app defined in application.js):
require(['marionette', 'application'],
function ( Marionette, App ) {
'use strict';
App.start();
});
config.js (Config for require.js)
require.config({
baseUrl: "/scripts",
/* starting point for application */
deps: ['marionette', 'main'],
shim: {
backbone: {
deps: [
'underscore',
'jquery'
],
exports: 'Backbone'
},
marionette: {
deps: ['backbone'],
exports: 'Marionette'
}
},
paths: {
backbone: '../bower_components/backbone/backbone',
jquery: '../bower_components/jquery/dist/jquery',
underscore: '../bower_components/underscore/underscore',
/* alias all marionette libs */
'marionette': '../bower_components/marionette/lib/core/backbone.marionette',
'backbone.wreqr': '../bower_components/backbone.wreqr/lib/backbone.wreqr',
'backbone.babysitter': '../bower_components/backbone.babysitter/lib/backbone.babysitter'
}
});
It looks like you're missing a reference to the router's controller.
Try updating the Router to include a reference to myController:
App.Router = Marionette.AppRouter.extend({
controller: myController,
appRoutes: {
"home": "home"
}
});
See AppRouter docs for more infomation:
http://marionettejs.com/docs/v2.4.1/marionette.approuter.html
It seems that initialize:after in:
App.on("initialize:after", function () {
if (Backbone.history) {
Backbone.history.start();
}
});
isn't supported in newest versions of Marionette and I was supposed start instead:
App.on("start", function () {
if (Backbone.history) {
Backbone.history.start();
}
});
Most posts about Marionette seems to be rather outdated. Those are still really helpful but be sure to verify it with the official framework's documentation.
I should've done that in the first place..

React-router undefined after concatenation

I've set up an app with react using react-router for routing and are having issues bundling it all.
I'm trying to build/bundle all the js files using gulp-requirejs. But somehow the shim is not included, or the react-router is just ignored. Whatever the problem is, I just end up with an error in the browser console saying Uncaught Error: app missing react-router
I'm including the most important code, feel free to ask if something doesn't make sense.
gulpfile.js
Almond.js is there to replace requirejs
var gulp = require('gulp'),
uglify = require('gulp-uglify'),
rjs = require('gulp-requirejs'),
gulp.task('requirejsBuild', function() {
rjs({
baseUrl: './app/resources/js/',
out: 'app.min.js',
paths: {
'react': '../bower_components/react/react-with-addons',
'react-router': '../bower_components/react-router/dist/react-router',
'react-shim': 'react-shim',
'jquery': '../bower_components/jquery/dist/jquery'
},
shim: {
'react-shim': {
exports: 'React'
},
'react-router': {
deps: ['react-shim']
}
},
deps: ['jquery', 'react-router'],
include: ['init'],
name: '../bower_components/almond/almond'
})
.pipe(uglify()).pipe(gulp.dest('./app/resources/js/'));
});
init.js
require.config({
baseUrl: '/resources/js/',
deps: ['jquery'],
paths: {
'react': '../bower_components/react/react-with-addons',
'react-router': '../bower_components/react-router/dist/react-router',
'react-shim': 'react-shim',
'jquery': '../bower_components/jquery/dist/jquery'
},
shim: {
'react-shim': {
exports: 'React'
},
'react-router': {
deps: ['react-shim']
}
}
});
require(['react', 'app'], function(React, App) {
var app = new App();
app.init();
});
app.js
define([
'react',
'react-router',
], function(
React,
Router,
){
var Route = Router.Route;
var RouteHandler = Router.RouteHandler;
var DefaultRoute = Router.DefaultRoute;
/**
* Wrapper for it all
*
* #type {*|Function}
*/
var Wrapper = React.createClass({displayName: "Wrapper",
mixins: [Router.State],
render: function() {
return (
React.createElement(RouteHandler, null)
);
}
});
var routes = (
React.createElement(Route, {handler: Wrapper, path: "/"}, null)
);
var App = function(){};
App.prototype.init = function () {
Router.run(routes, Router.HistoryLocation, function (Handler) {
React.render(React.createElement(Handler, null), document.getElementById('content'));
});
};
return App;
}
);
index.html
Mainly containing a script tag
After build you have to manually swap the src with app.min.js
<script data-main="/resources/js/init" src="/resources/bower_components/requirejs/require.js"></script>

Configuring require.js for backbone-ui

I am trying to use the backbone-ui library but cannot figure out the require.js configuration to get the modules loaded.
main.js:
requirejs.config({
baseUrl: '/static/js/facebook_report_app/js',
paths: {
backbone: 'lib/backbone'
, underscore: 'lib/underscore'
, jquery: 'lib/jquery'
, laconic: 'lib/laconic'
, moment: 'lib/moment'
, backboneUI: 'lib/backbone-ui/js/backbone_ui'
, menuUI: 'lib/backbone-ui/js/menu'
, textUI: 'lib/backbone-ui/js/text_field'
, text: 'lib/text'
},
shim: {
'lib/underscore': {
exports: '_'
},
'laconic': {
deps: ["jquery"],
exports: "$.el"
},
'lib/backbone': {
deps: ['lib/underscore']
, exports: 'Backbone'
},
'backboneUI': {
deps: ['lib/backbone', 'laconic', 'jquery']
, exports: 'Backbone.UI'
},
'textUI': {
deps: ['jquery', 'lib/backbone', 'backboneUI', 'laconic']
, exports: 'Backbone.UI.TextField'
},
'menuUI': {
deps: ['lib/backbone', 'backboneUI', 'laconic', 'textUI']
, exports: 'Backbone.UI.Menu'
},
'lib/backgrid': {
deps: ['lib/underscore', 'lib/backbone']
, exports: 'Backgrid'
},
'report_app': {
deps: ['lib/underscore', 'lib/backbone', 'lib/backgrid', 'backboneUI']
}
}
});
require([
'facebook_report_app'
],
function(FacebookReportApp) {
window.fbReport = new FacebookReportApp();
});
menu_user.js
define(['jquery', 'lib/backbone', 'backboneUI', 'menuUI', 'laconic'], function(AccountPickerView) {
var AccountPickerView = Backbone.UI.Menu.extend({
el: '.left-nav',
});
return AccountPickerView;
});
When I load this in dev, the console reports "Object [object Object] has no method 'input' ", on line 44 of the text_field.js of the Backbone-UI library.
I suppose my configuration approach is broken to begin with -- I added the menu.js and text_field.js files bc I was getting errors 'Backbone.UI.Menu' and Backbone.UI.TextField' (a requirement of Menu) weren't defined. But there must be a cleaner way to bring in the various files of backbone-ui.
So how do I get rid of the 'no method input' error? Or better configure to use Backbone UI? Or should I be using jQuery UI in the first place? In which case, where do I go to figure out configuration of that?
I got it working, after much fiddling with the following setup:
js/main.js
requirejs.config({
baseURL: 'js',
urlArgs: "bust=" + (new Date()).getTime(),
shim: {
underscore: {
exports: '_'
},
jquery: {
exports: '$'
},
backbone: {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
laconic: {
exports: '$.el'
},
backbone_ui: {
deps: ['underscore', 'jquery', 'backbone', 'laconic', 'moment'],
exports: 'Backbone.UI'
}
},
paths: {
jquery: 'http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min',
moment: './lib/moment.min',
laconic: './lib/laconic',
underscore: 'http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min',
backbone: 'http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min',
backbone_ui: './lib/backbone-ui',
crypto: 'http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/md5',
templates: '../templates',
collections: './collections',
models: './models',
}
});
js/views/json.js
define(['jquery','underscore', 'backbone', 'backbone_ui'],
function($,_,Backbone, BBUI){
var JsonView = Backbone.View.extend({
className: "json-item",
initialize: function(data){
var self = this;
this.app = data.app;
this.model = data.model;
this.listenTo(this.model, "change", function(){
console.log("model changed", self.model);
});
this.model.fetch({
success: function(){
self.render();
}
});
},
render: function(){
var self = this;
$(this.el).empty();
for (key in this.model.attributes){
this.el.appendChild(new Backbone.UI.Label({content:key}).render().el);
this.el.appendChild(new Backbone.UI.TextField({model: this.model, content:key}).render().el);
}
this.el.appendChild(new Backbone.UI.Button({content:"save", onClick: function(){self.model.save()}}).render().el);
return this;
}
});
return JsonView;
});
Please note that I import backbone-ui as BBUI and never reference it that way. BBUI.TextField() is a defined function and using it would work as well, but the way Backbone-ui is set up it makes alterations to Backbone, Jquery, and Underscore when it loads. So I figured I just needed it to be run prior to the view getting loaded.

Getting blank page using RequireJS and Grunt

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!

Unable to resolve _ in a Backbone & RequireJS app

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.

Categories