AMD Module Loading Error with Mustache using RequireJS - backbone.js

I am following the tuturoial here: http://backbonetutorials.com/organizing-backbone-using-modules/ and all I would like to do is use Mustache instead of underscore.js for my templating engine in a Backbone View. Everything is working as expected until I try to do the replacement of Mustache. Firebug gives me this:
Load timeout for modules: Mustache
My Mustache wrapper (in libs/mustache/mustache-wrap.js) is like so:
define(['libs/mustache/mustache'], function(){
// Tell Require.js that this module returns a reference to Mustache
return Mustache;
});
Here is the code for my Backbone View:
// Protocol Detail View
define([
'jQuery',
'Underscore',
'Backbone',
'Mustache',
'collections/protocols',
'text!templates/protocol/protocoldetail.html'
], function($, _, Backbone, Mustache, protocolCollection, protocolDetailTemplate){
var protocolDetailView = Backbone.View.extend({
el: "#asset-detail",
render: function( pid ){
this.collection = new protocolCollection;
this.collection.fetch();
var p = this.collection.getByCid('c'+pid);
var template = "{{name}}";
htmlr = Mustache.to_html(template, p);
$(this.el).html(htmlr);
//var compiledTemplate = _.template( protocolDetailTemplate, { protocol: protocol });
//$(this.el).html(compiledTemplate);
},
events: {
"submit #asset-owner": "chown"
},
chown: function ( pid ){
console.log("Protocol Detail View chown callback.")
}
});
return new protocolDetailView;
});
My main.js file has the following config:
require.config({
paths: {
jQuery: 'libs/jquery/jquery',
jQueryUI: '//ajax.aspnetcdn.com/ajax/jquery.ui/1.8.17/jquery-ui.min',
jstree: 'libs/jstree/jquery.jstree',
Mustache: 'libs/mustache/mustache-wrap',
Underscore: 'libs/underscore/underscore',
Backbone: 'libs/backbone/backbone'
}
});

In you main.js file where you have all you're requires, make sure to add Mustache to the config, and don't worry about the wrapper and just try loading Mustache directly.
require.config({
'paths': {
"underscore": "libs/underscore",
"backbone": "libs/backbone",
"Mustache": "libs/mustache/mustache"
}
});
That might help...
Also, here are some starter apps to help you out on your require, backbone journey.
https://github.com/jcreamer898/RequireJS-Backbone-Starter
https://github.com/david0178418/BackboneJS-AMD-Boilerplate
https://github.com/addyosmani/backbone-fundamentals
https://github.com/amdjs

Clone the repository from github:
$ git clone https://github.com/janl/mustache.js.git
Then, build the RequireJS specific version of the library:
$ rake requirejs
Use the resulting file 'requirejs.mustache.js' as your mustache library.

Use Twitter's mustache repository!
Here is what worked for me (Ubuntu 12.04):
sudo apt-get install rake ruby-rspec
git clone git://github.com/twitter/mustache.js.git
cd mustache.js/
rake requirejs

Related

r.js cannot resolve dependencies mentioned in shim

I've recently joined a project which is built using Backbonejs, (uses Marionette for view rendering) + nodejs. They also use requirejs to load the backbonejs files. Would like to add at this stage, that I've never worked with backbonejs or requirejs before and hence I'm struggling with the issue I describe later.
Some code that will help explain the issue that I run into (All this code was already written by previous dev's)
Folder Structure:
/public
/js
/collection (consists all Backbone.js collections files)
/lib
/bower_components
/backone
/marionette
/etc
/models (consists all Backbone.js models files)
/views (consists all Backbone.js view files)
/main.js
/main.build.js
/app.js
/controller.js
/router.js
Code from files that I think relate to issue:
main.js
requirejs.config({
paths: {
'async': 'lib/bower_components/requirejs-plugins/src/async',
'jquery': 'lib/bower_components/jquery/dist/jquery.min',
'underscore': 'lib/bower_components/underscore/underscore-min',
'lodash': 'lib/bower_components/lodash/dist/lodash.min',
'backbone': 'lib/bower_components/backbone/backbone',
'marionette': 'lib/bower_components/marionette/lib/backbone.marionette.min',
'markercluster':'lib/markercluster',
'jquerymobile': 'lib/jquery.mobile-1.4.0.min',
'hogan': 'lib/template-2.0.0.min',
'templates': '/templates',
'real': 'lib/mainjs',
'touch': 'lib/jquery.touchSwipe.min',
'mouse': 'lib/jquery.mousewheel',
'moment': 'lib/moment-2.5.1.min',
'humanize': 'lib/bower_components/humanize-plus/public/dist/humanize.min',
'validator': 'lib/bower_components/validator-js/validator.min',
'real': 'lib/mainfile'
},
shim: {
backbone: {
deps: ["underscore"]
},
marionette: {
deps: ["backbone"]
},
templates: {
deps: ["hogan", "jquery"]
},
real: {
deps: ["jquery", "jquerymobile", "touch", "mouse"]
},
markercluster: {
exports: "MarkerClusterer"
},
humanize: {
exports: "humanize"
}
},
waitSeconds: 0
});
define('gmaps', ['async!http://maps.google.com/maps/api/js?v=3&key=AIzaSyBiV8f88yLWJ_IMSdP1fVNO1-gt3eLVSgg&sensor=true&callback=gMapsCallback'], function(){
// define('gmaps', ['http://maps.google.com/maps/api/js?v=3&sensor=false'], function(){
return window.google.maps;
});
require(['app', 'templates', 'real'], function(app) {
app.start({
version: "0.9.9"
});
});
main.build.js
({
baseUrl: ".",
name: "main",
wrapShim: true,
out: "main-built.js"
})
app.js
define(['underscore', 'controller', 'router', 'models/Cache', 'views/RootView'], function(_, Controller, Router, Cache, RootView) {
var Application = Marionette.Application.extend({
propertyListPageSize: 3,
initialize: function() {
_.templateSettings = { interpolate : /\{\{(.+?)\}\}/g };
},
onStart: function(options){
new RootView();
this.controller = new Controller();
this.router = new Router({controller: this.controller});
this.cache = new Cache();
this.context = {};
//this.evHistory = [];//#todo remove once BB/marionette navigation is in place
if(Backbone.history) Backbone.history.start({ pushState: false });
if(Backbone.history.fragment === "") this.navigate('home');
},
navigate: function(fragment, trigger, replace){
this.router.navigate(fragment, {trigger:trigger, replace:replace});
},
back: function() {
window.history.back();
}
});
app = new Application();
return app;
});
rootView.js
define(['marionette', 'views/HomeView', 'views/HeaderView', 'views/FooterView', 'views/MenuView', 'views/VideoView', 'views/LocationSearchView', 'views/LoginView', 'views/FindView', 'views/ServicesView', 'views/ValueView', 'views/PropertyListView', 'views/SideBySideView', 'views/ConfirmRegistrationView', 'views/ForgotPasswordView', 'views/CreateAccountView', 'views/UserHomeView', 'views/MyBrokerView', 'views/GiveFeedbackView', 'views/SeeFeedbackView', 'views/ViewingScheduleView', 'views/MyViewingsSummaryView', 'views/MyAccountView', 'views/ViewingConfirmView', 'views/ValueAddressPropertyListView'],
function(Marionette, HomeView, HeaderView, FooterView, MenuView, VideoView, LocationView, LoginView, FindView, ServicesView, ValueView, PropertyListView, SideBySideView, ConfirmRegistrationView, ForgotPasswordView, CreateAccountView, UserHomeView, MyBrokerView, GiveFeedbackView, SeeFeedbackView, ViewingScheduleView, MyViewingsSummaryView, MyAccountView, ViewingConfirmView, ValueAddressPropertyListView) {
var RootView = Marionette.LayoutView.extend({
...some view code
});
Use case I'm trying to solve:
So when I access the site in the browser, I notice in the debugger that it loads all the js files right at the beginning. During the load process my site is blank and user has to wait a while before he can use the site.
So what I've been able to understand is that when app is 'started' in main.js, app.js creates an instance of rootView.js , which in turn has all the views listed as dependencies. This triggers a download request for all the other views which in turn would solve their own dependencies and download all the relevant models and collections. Hence all files being downloaded when the user accessed the site.
Solution I've been trying:
Since requirejs is being used, I'm trying to use r.js to optimize and combine all the js files to reduce the number of downloads.
Issue I'm running into:
When i run r.js. i get the following error
Tracing dependencies for: main
Error: ENOENT: no such file or directory, open '/var/node_projects/rm/rm.src.server/src/public/js/underscore.js'
In module tree:
main
app
Error: Error: ENOENT: no such file or directory, open '/var/node_projects/rm/rm.src.server/src/public/js/underscore.js'
In module tree:
main
app
at Error (native)
If I add the underscore.js files directly to the specified path in the error, then I get the same error for marionette.js. What I think is happening is that app.js is not recognizing the shim'ed dependencies and hence its trying to find the files directly at specified path in the error.
Things I've tried:
- I've added wrapShim: true in the main.build.js file but that did not help
Honestly, I've been sitting on this for a couple of days and I'm not sure what I can do next and hence this post.
Any help/direction would be appreciated.
You need to include the same shim configuration in your build file, as wrapShim is not sufficient.
If shim config is used in the app during runtime, duplicate the config here. Necessary if shim config is used, so that the shim's dependencies are included in the build. Using "mainConfigFile" is a better way to pass this information though, so that it is only listed in one place. However, if mainConfigFile is not an option, the shim config can be inlined in the build config.
https://github.com/jrburke/r.js/blob/master/build/example.build.js

JST is undefined - Yeoman , Backbone - Template cannot be loaded

Am new to Yeoman and I generated a Backbone application using generator-backbone
This is my main.js ( require js config)
/*global require*/
'use strict';
require.config({
shim: {,
handlebars: {
exports: 'Handlebars'
}
},
paths: {
jquery: '../bower_components/jquery/dist/jquery',
backbone: '../bower_components/backbone/backbone',
underscore: '../bower_components/lodash/dist/lodash',
handlebars: '../bower_components/handlebars/handlebars'
}
});
require([
'backbone'
], function (Backbone) {
Backbone.history.start();
});
Now I created a view using yo backbone:view Login
This is the generated view
define([
'jquery',
'underscore',
'backbone',
'templates'
], function ($, _, Backbone, JST) {
'use strict';
var LoginViewView = Backbone.View.extend({
template: JST['app/scripts/templates/LoginView.hbs'],
tagName: 'div',
id: '',
className: '',
events: {},
initialize: function () {
this.listenTo(this.model, 'change', this.render);
},
render: function () {
this.$el.html(this.template(this.model.toJSON()));
}
});
return LoginView;
});
When I run the app with LoginView, i get an error
Error: Script error for: templates http://requirejs.org/docs/errors.html#scripterror
Apparently I see templates is no where defined in main.js. What am i missing while running the yeoman generator
If you did the same blunder mistake like m, just verify this
After generating the code, and if its shows template is undefined or u find the template.js missing, check the following steps
run grunt handlebars (include --force if you want to ignore any warning/errors)
This will pre compile the .hbs file make a single template.js file.
But the catch here is, it wont work out of the box, the template.js is written in the location app/.tmp/scripts/template.js location.
You can modify main require configure file accordingly, or open GruntFile.js and modify this function
grunt.registerTask('createDefaultTemplate', function () {
grunt.file.write('/your/custom/path/to/templates.js', 'this.JST = this.JST || {};');
});
Also verify if u have this line in GruntFile.js
grunt.loadNpmTasks('grunt-contrib-handlebars');
if not, add it at the very last (ofcourse not after the function block)

how can I use external templates with Marionette Backbone

How exactly do I use an external template for my Marionette ItemView?
I read so many 'methods' I can't get any of them working...
JST Method ... I'm not on rails so can't use this
Backbone.Marionette.Renderer.render = (template, data) ->
path = JST["backbone/apps/" + template]
unless path
throw "Template #{template} not found!"
path(data)
RequireJS Method ... I'm not using require js
var tpl = require(inject[this.templateName]);
this.template = _.template(tpl);
What method should I be using?
I use Handlebars for my templating engine and hbs to retrieve the precompiled resource via require.js, that way all I have to do is define the template and set it as the ItemView's template; marionette does the rest.
Here's an example
View - welcome.js
define([
'app',
'jquery',
'backbone',
'marionette',
'hbs!templates/welcome'
],
function(App, $, Backbone, Marionette, template) {
return Backbone.Marionette.ItemView.extend({
template: template,
});
});
Template - welcome.html
<div>
<h1>Hello World</h1>
</div>
If you're not using handlebars, or can't use hbs, then something similar can be done with text.js - https://github.com/requirejs/text

requirejs + backbonejs + optimizer = backbone undefined

Backbone doesn't get called in the indexview module.
using requirejs 2.1.5/2.1.4 and backbonejs 0.9.10
main.js after running r.js
...
// this is causing the backbone to return
// null/undefined in the next define call below
define("backbone", function(){});
define('views/index/IndexView', [
'underscore',
'backbone',
'text!templates/index/indexTemplate.html'
], function(_, Backbone, indexTemplate){
console.log(Backbone); // returns undefined
var IndexView = Backbone.View.extend({
...
BUT if I take out the first define call that registers backbone as a module, everything
works fine. but backbone-min.js gets loaded separately. but for now it's the only way
to make the script run. I am definitely missing something here.
main.js
require.config({
paths: {
underscore : 'libs/underscore/underscore-min',
backbone : 'libs/backbone/backbone-min'
templates : '../templates'
},
shim: {
'backbone': {
deps: ['jquery','underscore'],
exports: 'Backbone'
}
}
});
require(['app'], function(App){
App.initialize();
});
build.js
({
appDir: "../",
baseUrl: "js",
dir: "../../build",
optimize: "none",
paths: {
"jquery": "libs/requirejs/require-jquery",
"underscore" : 'libs/underscore/underscore-min',
"backbone": 'libs/backbone/backbone-min',
"templates": '../templates',
},
modules: [
{
name: "main",
exclude: ["jquery"]
}
]
})
I'm still getting my feet wet with backbone and requirejs.
any feedback is much appreciated.
First of all, you don't need that define('backbone',...). What is that part for anyways? You don't need to define Backbone as a module. Requirejs is doing the job of making Backbone available for you to use throughout your framework. As you can see in your code, by calling Backbone.View.extend(), Backbone already exists. If you want to inspect it, don't use console.log, use console.dir instead. In the chrome inspector it formats the output nicely.
Secondly, add underscore to the backbone deps array in your shim.
I've just had this issue, you need to add the 'shim' from your main.js to your build.js file, and will work like a charm ;)

Requirejs2: How to handle own files?

I have configured requirejs to load the core libs (jquery, underscore, backbone).
Now I would like to add my backbone models, controllers, views, etc to be loaded asyncronly
I found a lots of tutorials to this topic and lots of "ready" boilerplates unfortunatly I mentioned that most approaches are depreceated or rather complicated (even there are better approaches).
One example is how I configured requirejs for the main libs:
https://stackoverflow.com/a/10914666/1309847
So how do I load Backbone Views, Models, Collections, Routers, Controllers and Templates with a simple and valid Requirejs configuration?
I followed youre advice but get some strange error
main.js
require.config({
paths: {
jquery: 'vendors/jquery/jquery',
underscore: 'vendors/underscore/underscore',
backbone: 'vendors/backbone/backbone'
},
shim: {
underscore: {
exports: '_'
},
backbone: {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
}
}
});
require(['app'], function(app){
});
app.js
define(['jquery', 'underscore', 'backbone'], function($, _, Backbone){
var Message = new Backbone.Model.extend({
//idAttribute: '_id',
//defaults: { body: '' }
//url: function(){ return this.id ? '/messages/' + this.id : '/messages'; }
});
var newMessage = new Message({ body: 'hi' });
newMessage.save();
});
The error occours in app.js:
Uncaught TypeError: Object [object Object] has no method 'apply'
When I comment the new Backbone.Model.extend part I don't get any error anymore.
in my experience, the best way to bootstrap your application is by creating a Backbone.Router. So you can associate urls with your application functionality.
If you are using RequireJS+Backbone, you probably have a main.js where RequireJS is configured (paths, shims, etc). The first call to "require" is used to load a initial script in order to bootstrap the whole app.
For example:
/**
* main.js - RequireJS bootstrap
*/
require.config({
paths: {
//your paths
},
shim: {
//your shims
}
});
require(
[
'app' //app.js is at the same directory as main.js
],
function(app) {
app.init();
}
);
then in app.js you can create a new Router instance, or you can just start creating Views and Models.
For further reference: http://addyosmani.github.com/backbone-fundamentals/
So as I have now understood right: You have to wrap a requirejs function around youre own custom js file.
The function is called define. The first parameter is an array of the dependencies which you have defined in the main.js file or a relative path to another custom js from you.
The second parameter is the callback which holds the original file. Important is that you return the object, function, array or variable which you want to share.
The whole thing looks like this:
define(
['underscore', 'backbone'], // the dependencies (either relative paths or shortcuts defined in main.js
function(_, Backbone){ // the return statement of the deps mapped to a var
var MessageModel = Backbone.Model.extend({ // the original code, file
defaults: { body: '' },
initialize: function(){}
});
return MessageModel; // the return statement, sharing the "final result", sometimes you return the initialize parameter
});
The same for a collection wrapping the models:
define(
['jquery', 'underscore', 'backbone', 'models/message_model'], // deps and the last one is the relative path
function($, _, Backbone,MessageModel){ // same as above explained
var MessageCollection = Backbone.Collection.extend({
model: MessageModel,
initialize: function(){}
});
return MessageCollection;
});
I now only have to figure out how I can bootstrap to whole application. But I think I need more knowledge of backbone to do this :)

Resources