Using require.js dependency injection - javascript

I am trying to make a module that uses jQuery and Handlebars
This is the main file:
require(['app', 'jquery', 'handlebars' ], function (app, $, handlebars) {
console.log('Running jQuery %s', $().jquery);
});
And this is the app file:
define(['jquery', 'handlebars'], function ($, hb) {
$(function() {
var source = $("#some-template").html();
var template = hb.compile(source);
var data = {...});
});
Why is does it say hb is not defined but when I remove all dependencies it works when using Handlebars instead of hb (which is the normal way)?

Handlebars is not AMD/RequireJS compliant. You will need to shim it: http://requirejs.org/docs/api.html#config-shim
shim: {
handlebars: {
exports: 'Handlebars'
},
}

Related

How to load jQuery Migrate for jQuery via RequireJS?

Can I load jQuery migrate via RequireJS? I don't understand how the timing can be handled correctly. See this example:
require([
'jquery',
'jqmigrate'
], function ($) {
if ($.browser.msie) {...}
});
Isn't is possible that jqmigrate will load before jquery? Also, I do not want to keep loading jqmigrate explicitly in every module. Any way to do this in the require.config so it loads jqmigrate automatically when jQuery is required?
There are a couple of things you will need:
make sure jqmigrate depends on jquery.
you could write a wrapper module that include both, and return jquery, so your require.config could look like:
jquery-wrapper.js:
define(['jquery-src', 'jqmigrate'], function ($) {
return $;
})
require.config
{
paths: {
'jquery-src' : '/path/to/jquery',
'jqmigrate': '/path/to/jqmigrate',
'jquery': '/path/to/jquery-wrapper'
}
}
using shims worked for me. I did get stuck because i had pluralized shims its; shim
requirejs.config({
paths: {
'jquery': '//code.jquery.com/jquery-2.1.4',
'jquery-migrate': '//code.jquery.com/jquery-migrate-1.2.1'
},
shim: {
'jquery-migrate': { deps: ['jquery'], exports: 'jQuery' },
'foo': ['jquery']
}
});
require(['jquery-migrate', './foo'], ($, foo) => {
console.log('bootstrapped', $, foo);
});
jQuery Migrate 3.0.1 currently has a defect that renders it unusable for RequireJS or any AMD loader. A change is required to the UMD fragment before implementing the accepted answer:
define( [ "jquery" ], function ($) {
return factory($, window);
});
Details and solution are here.
jquery-migrate-wrapper.js
define(['jquery', 'jquery-migrate'], function ($) {
// additional initialization logic can be added here
$.UNSAFE_restoreLegacyHtmlPrefilter();
return $;
})
require-config.js
require.config({
...otherConfigOptions,
shim: {
...otherShimSettings,
'jquery-migrate':{deps: ['jquery']},
},
map: {
// provides 'jquery-migrate-wrapper' for all (*) modules that require'jquery'
'*': { 'jquery': 'jquery-migrate-wrapper' },
// but provides the original 'jquery' for 'jquery-migrate-wrapper' and
// 'jquery-migrate'
'jquery-migrate-wrapper': { 'jquery': 'jquery' },
'jquery-migrate': {'jquery': 'jquery'}
}
})

Why does my Handlebars not have a compile method?

I am setting up a Backbone project with Handlebars and I am having an issue with Handlebars not finding the compile method. Here is my config file:
require.config({
hbs: {
templateExtension: '.hbs'
},
paths: {
backbone: "libs/backbone/backbone",
handlebars: 'libs/handlebars/handlebars.amd',
hbs: 'libs/requirejs-hbs/hbs',
jquery: 'libs/jquery/jquery',
jqueryMockAjax: 'libs/jquery-mockjax/jquery.mockjax',
text: 'libs/requirejs-text/text',
templates: 'templates/',
underscore: 'libs/underscore/underscore'
},
shim: {
backbone: {
deps: [
'underscore',
'jquery'
],
exports: 'Backbone'
},
hbs: {
deps: ['handlebars'],
exports: 'hbs'
},
jqueryMockAjax: {
deps: [ 'jquery' ],
exports: '$.mockjax'
},
underscore: {
exports: '_'
}
}
});
require(['app'], function(App) {
'use strict';
var app = new App();
app.render();
});
Here is the app.js that I am trying to render:
define(function(require) {
var Backbone = require('backbone');
var testTemplate = require('hbs!templates/test');
var router = Backbone.View.extend({
el: $('body'),
template: testTemplate,
render: function() {
return $(this.el).html(this.template());
}
});
return router;
});
When Handlebars calls the hbs.js file on line 25 it cannot find the compile function
define(["handlebars"], function(Handlebars) {
var buildMap = {},
templateExtension = ".hbs";
return {
// http://requirejs.org/docs/plugins.html#apiload
load: function (name, parentRequire, onload, config) {
// Get the template extension.
var ext = (config.hbs && config.hbs.templateExtension ? config.hbs.templateExtension : templateExtension);
if (config.isBuild) {
// Use node.js file system module to load the template.
// Sorry, no Rhino support.
var fs = nodeRequire("fs");
var fsPath = config.dirBaseUrl + "/" + name + ext;
buildMap[name] = fs.readFileSync(fsPath).toString();
onload();
} else {
// In browsers use the text-plugin to the load template. This way we
// don't have to deal with ajax stuff
parentRequire(["text!" + name + ext], function(raw) {
// Just return the compiled template
****HERE onload(Handlebars.compile(raw));
});
}
},
// http://requirejs.org/docs/plugins.html#apiwrite
write: function (pluginName, name, write) {
var compiled = Handlebars.precompile(buildMap[name]);
// Write out precompiled version of the template function as AMD
// definition.
write(
"define('hbs!" + name + "', ['handlebars'], function(Handlebars){ \n" +
"return Handlebars.template(" + compiled.toString() + ");\n" +
"});\n"
);
}
};
});
The Handlebars variable gives me the Handlebars environment, but it has an extra layer in it, so I have to change that line to Handlebars.default.compile(raw). Where is that default object coming from and how do I get rid of it? I wouldn't worry about it, but if I pull down this project somewhere else I am always going to have to remember to do that.
I just encountered this myself, using Handlebars for this first time. It's likely that you're using the "runtime" build of Handlebars. I included this one in my requirements, mistakenly assuming it was the minified version or something.
But in fact the runtime version is significantly smaller as it excludes the template compiler, and is for use only with pre-compiled templates. If you're compiling the template client-side then you need the full version from http://builds.handlebarsjs.com.s3.amazonaws.com/handlebars-v3.0.3.js (Note: This link may be out of date; you're probably better off going directly to handlebarsjs.com and looking for the current download for the "full version", as opposed to runtime.)
Otherwise, you can follow the instructions on the Handlebars website to run the template compiler. You need node for this. The template compiler produces a JavaScript file containing the pre-compiled template code which you need to link to your page along with the Handlebars runtime build.
Here is how I fixed this issue, although I do not understand completely why the configuration above did not work. The hbs plugin had a folder with all the dependencies it needed in it, like handlebars. When I referred to the handlebars copy contained in the hbs directory, then everything worked like it was supposed to. I do not understand why the vanilla copy of handlebars did not work. I was not using the handlebars runtime, it was the full version, but still there was an issue. After I resolved this, then my template stuff just worked.

jQueryMobile and backbone - how to load "routers/mobileRouter"

I'm trying to setup a project using jQueryMobile, Backbone and RequireJs. Here is the relevant code snippet:
require([ "jquery", "backbone", "routers/mobileRouter" ],
function( $, Backbone, Mobile ) {
/* do something */
}
) ;
It is actually coming from here. Running the code gives a 404 on 'routers/mobileRouter'
GET http://localhost:9000/scripts/routers/mobileRouter.js 404 (Not Found)
For example, if I search for 'mobileRouter.js' in my project I get the following
./app/bower_components/jquery-mobile/demos/examples/backbone-require/js/routers/mobileRouter.js
./app/bower_components/jquery-mobile/dist/demos/examples/backbone-require/js/routers/mobileRouter.js
These are demos/examples, so how should I load this, maybe I need to install an other package ? Any link to some documentation about this would of course help me too!
UPDATE: here is all the js code
// Sets the require.js configuration for your application.
require.config( {
// 3rd party script alias names (Easier to type "jquery" than "libs/jquery-1.8.3.min")
paths: {
// Core Libraries
jquery: '../bower_components/jquery/jquery',
backbone: '../bower_components/backbone/backbone',
underscore: '../bower_components/underscore/underscore',
jquerymobile:'../bower_components/jquery-mobile/dist/jquery.mobile.min'
},
// Sets the configuration for your third party scripts that are not AMD compatible
shim: {
"backbone": {
"deps": [ "underscore", "jquery" ],
"exports": "Backbone" //attaches "Backbone" to the window object
},
"jquery.mobile": ['jquery']
} // end Shim Configuration
} );
// Includes File Dependencies
require([ "jquery", "backbone", "routers/mobileRouter" ], function( $, Backbone, Mobile ) {
$( document ).on( "mobileinit",
// Set up the "mobileinit" handler before requiring jQuery Mobile's module
function() {
// Prevents all anchor click handling including the addition of active button state and alternate link bluring.
$.mobile.linkBindingEnabled = false;
// Disabling this will prevent jQuery Mobile from handling hash changes
$.mobile.hashListeningEnabled = false;
}
);
require( [ "jquerymobile" ], function() {
// Instantiates a new Backbone.js Mobile Router
this.router = new Mobile();
});
} );
Just add another key/value to your paths:
paths: {
// Core Libraries
jquery: '../bower_components/jquery/jquery',
backbone: '../bower_components/backbone/backbone',
underscore: '../bower_components/underscore/underscore',
jquerymobile:'../bower_components/jquery-mobile/dist/jquery.mobile.min',
jquerymobilerouter: '../bower_components/jquery-mobile/demos/examples/backbone-require/js/routers/mobileRouter.js'
},
then you can use it like this:
require(["jquery", "backbone", "jquerymobilerouter"], function($, Backbone, MobileRouter) {
});

How to Override a model/ view file at runtime, for a js file combined by requirejs optimizer?

Scenario:
Framework used are backbone and require.
I have a main.js which have several dependencies on util, model and view js, which are again inter-dependent. There are cyclic dependencies also.
This main.js has been compiled into a single file using requirejs optimizer.
Problem:
How to override certain views and models at runtime?
(I have a single compiled version of main, so i am not talking about excluding the js for models or views at compile time).
At compile time i don't know whether the model/view would be over-ridden. So when i run the optimizer a single js file with all the models and views is created.
I need to override a particular class definition in that single js file, such that i don't modify that file.
Is there any configuration which will tell 'require' to load the model/view from a separate file rather than that single compiled js file?
or is there any way this could be achieved, with minimal changes?
//models/ - folder
//mymodel.js - filename
define([
'jquery',
'underscore',
'backbone'
], function($, _, Backbone) {
var mymodel2 = Backbone.Collection.extend({
//some code
});
return mymodel2;
});
//mymodel2.js - filename
define([
'jquery',
'underscore',
'backbone',
'mymodel'
], function($, _, Backbone, mymodel) {
var mymodel2 = Backbone.Collection.extend({
//some code
});
return mymodel2;
});
//views/ - folder
//view1.js - filename
define([
'jquery',
'underscore',
'backbone',
'runtime/util/logmanager',
'runtime/util/logger'
], function($, _, Backbone, LogManager, Logger) {
var view1 = Backbone.View.extend({
_configure: function(options) {
//some code
},
initialize: function() {
//some code
},
endsWith: function(str, suffix) {
//some code
}
});
return view1;
});
//like this i have view2.js, view3.js... etc
//Similarly i have util folder with util1.js, util2.js... etc
//main.js
;(function(){
if (!window.console) window.console = {};
if (!window.console.log) window.console.log = function () { };
var paths = {
jquery: 'libs/jquery/jquery',
underscore: 'libs/underscore/underscore',
initializer: 'runtime/initializer/initializer',
backbone: 'libs/backbone/backbone',
json2: 'libs/json/json2',
text: 'libs/require/text',
jqueryform: 'libs/jqueryform/jqueryform',
jqueryui: 'libs/jqueryui/jquery-ui',
slimscroll: 'libs/slimscroll/slimScroll',
i18next: 'libs/i18next/i18next',
common: 'libs/commons/common',
utility1 : 'util/util1',
utility2 : 'util/util2',
.
.
model2 : 'model/mymodel2',
.
.
.
view2 : 'view/view1'
};
window.configData = window.configData || {};
window.configData.serverPath = location.protocol + "//" + window.location.host;
require.config({
paths: paths,
shim: {
'underscore': {
exports: '_'
},
'backbone': {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
'i18next': {
deps: ['jquery', 'json2'],
exports: 'i18n'
}
}
});
require(['router'],
function(Router) {
Router.initialize();
});
})();
compiled/ combined file will look something like:
*! jQuery v1.7.1 jquery.com | jquery.org/license */
(//jquery-def file code)(window);
// Underscore.js 1.3.3
// (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
// Underscore is freely distributable under the MIT license.
// Portions of Underscore are inspired or borrowed from Prototype,
// Oliver Steele's Functional, and John Resig's Micro-Templating.
// For all details and documentation:
// http://documentcloud.github.com/underscore
(function() {
//uderscore code
}).call(this);
define("underscore", (function (global) {
return function () {
var ret, fn;
return ret || global._;
};
}(this)));
.
.
.
all lib definition
.
.
then depending on the dependencies models, views, utils, routers, definition
.
.
and finally main
;(function(){
if (!window.console) window.console = {};
if (!window.console.log) window.console.log = function () { };
var paths = {
jquery: 'libs/jquery/jquery-min',
underscore: 'libs/underscore/underscore',
initializer: 'runtime/initializer/initializer',
backbone: 'libs/backbone/backbone',
json2: 'libs/json/json2',
text: 'libs/require/text',
bootstrap: 'libs/bootstrap/bootstrap',
jqueryform: 'libs/jqueryform/jqueryform',
jqueryui: 'libs/jqueryui/jquery-ui',
slimscroll: 'libs/slimscroll/slimScroll',
i18next: 'libs/i18next/i18next',
common: 'libs/commons/common',
utility1 : 'util/util1',
utility2 : 'util/util2',
.
.
model2 : 'model/mymodel2',
.
.
.
view2 : 'view/view1'
};
window.configData = window.configData || {};
window.configData.serverPath = location.protocol + "//" + window.location.host;
require.config({
paths: paths,
shim: {
'underscore': {
exports: '_'
},
'backbone': {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
'i18next': {
deps: ['jquery', 'json2'],
exports: 'i18n'
}
}
});
require(['router'],
function(Router) {
Router.initialize();
});
})();
define("main", function(){});
Is there any configuration which will tell 'require' to load the
model/view from a separate file rather than that single compiled js
file?
To load a Javascript file using require, you can call it at any time (even after the optimizer has been run), like so:
myModule = require('myJavascriptFile');
The optimized file isn't designed to be manipulated. Modify your source, then re-optimize.
Also, note: Require does not compile your Javascript.
How to override certain views and models at runtime?
In Javascript, you can reassign variables at any time. Example:
var x = 1; // the value of x is 1
x = 2; // the value of x is now 2
Similarly, you can override Backbone Models and Views at runtime like so:
var myModel = new Backbone.Model({x: 1});// create myModel
myModel = new Backbone.Model({x: 2});// now, myModel is a different model
myModel = "something else entirely";// now, myModel is a string
You could override require() itself and make it look for the module in a directory first before loading it the way that it normally does.
This probably won't be easy to do.

require.js modules not loading properly

I have my bootstrap file which defines the require.js paths, and loads the app and config modules.
// Filename: bootstrap
// Require.js allows us to configure shortcut alias
// There usage will become more apparent futher along in the tutorial.
require.config({
paths: {
bfwd: 'com/bfwd',
plugins: 'jquery/plugins',
ui: 'jquery/ui',
jquery: 'jquery/jquery.min',
'jquery-ui': 'jquery/jquery-ui.min',
backbone: 'core/backbone.min',
underscore: 'core/underscore.min'
}
});
console.log('loading bootstrap');
require([
// Load our app module and pass it to our definition function
'app',
'config'
], 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
console.log('initializing app');
App.initialize();
});
app.js is loaded like it should, and it's dependencies are loaded. it's define callback is called, with all the correct dependencies passed as arguments. No error is thrown. HOWEVER, in the bootstrap's callback, App is undefined! no arguments are passed. What can be causing this? Here's my app file ( modified for space)
// Filename: app.js
define(
'app',
[
'jquery',
'underscore',
'backbone',
'jquery-ui',
'bfwd/core',
'plugins/jquery.VistaProgressBar-0.6'
],
function($, _, Backbone){
var initialize = function()
{
//initialize code here
}
return
{
initialize: initialize
};
}
);
As far as I am aware you should probably just drop the 'app' string in your app.js define method.
// Filename: app.js
define([
'jquery',
'underscore',
'backbone',
'jquery-ui',
'bfwd/core',
'plugins/jquery.VistaProgressBar-0.6'
], function($, _, Backbone){
...
);
Ok I had the same problem, the key is the jquery path alias you define. It turns out that RequireJS has some special handling for jquery. If you use the jquery module name it will do a little bit of magic there.
Depending on what you have in jquery.min.js it may cause some problems, also the jquery plugin you have there may be a problem. Here are the relevant lines of code from the RequireJS source:
if (fullName) {
//If module already defined for context, or already loaded,
//then leave. Also leave if jQuery is registering but it does
//not match the desired version number in the config.
if (fullName in defined || loaded[id] === true ||
(fullName === "jquery" && config.jQuery &&
config.jQuery !== callback().fn.jquery)) {
return;
}
//Set specified/loaded here for modules that are also loaded
//as part of a layer, where onScriptLoad is not fired
//for those cases. Do this after the inline define and
//dependency tracing is done.
specified[id] = true;
loaded[id] = true;
//If module is jQuery set up delaying its dom ready listeners.
if (fullName === "jquery" && callback) {
jQueryCheck(callback());
}
}
For me I have it setup such that I have a file called /libs/jquery/jquery.js which returns the jquery object (just a wrapper for RequireJS). What I ended up doing was simply changing the path alias from jquery to $jquery. This helps avoid the undesired magic behavior.
In the original tutorial I read they use jQuery which also works.
This is a simple example that might help get you started:
I've created a very simple module:
https://gist.github.com/c556b6c759b1a41dd99d
define([], function () {
function my_alert (msg) {
alert(msg);
}
return {
"alert": my_alert
};
});
And used it in this fiddle, with only jQuery as an extra dependency:
http://jsfiddle.net/NjTgm/
<script src="http://requirejs.org/docs/release/1.0.7/minified/require.js"></script>
<script type="text/javascript">
require.config({
paths: {
"jquery": "https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min",
"app": "https://gist.github.com/raw/c556b6c759b1a41dd99d/20d0084c9e767835446b46072536103bd5aa8c6b/gistfile1.js"
},
waitSeconds: 40
});
</script>
<div id="message">hello</div>
<script type="text/javascript">
require( ["jquery", "app"],
function ($, app) {
alert($.fn.jquery + "\n" + $("#message").text());
app.alert("hello from app");
}
);
</script>
This is how I do it with requirejs and backbone:
first, define main or bootstrap file with config:
// bootstrap.js
require.config({
paths: {
text: 'lib/text',
jQuery: 'lib/jquery-1.7.2.min',
jqueryui: 'lib/jquery-ui-1.8.22.custom.min',
Underscore: 'lib/underscore-1.3.3',
Backbone: 'lib/backbone-0.9.2'
},
shim: {
'Underscore': {
exports: '_'
},
'jQuery': {
exports: 'jQuery'
},
'jqueryui': {
exports: 'jqueryui'
},
'Zepto': {
exports: '$'
},
'Backbone': {
deps: ['Underscore', 'Zepto'],
exports: 'Backbone'
}
});
define(function (require) {
'use strict';
var RootView = require('src/RootView');
new RootView();
});
Then, I use this syntax to load my scripts. I find it easier than the array notation to just define my depencies via var declarations.
// rootview.js
define(function (require) {
'use strict';
var $ = require('Zepto'),
Backbone = require('Backbone'),
LoginView = require('./LoginView'),
ApplicationView = require('./ApplicationView'),
jQuery = require('jQuery').noConflict();
return Backbone.View.extend({
// append the view to the already created container
el: $('.application-container'),
initialize: function () {
/* .... */
},
render: function () {
/* .... */
}
});
});
Hope it helps!
This is a bit late, but I just had this problem. My solution can be found here:
https://stackoverflow.com/questions/27644844/can-a-return-statement-be-broken-across-multiple-lines-in-javascript
I posted that question for a different reason, to ask why my fix worked in the first place. Elclanrs provided the perfect answer. To make a long story short, the undefined is probably appearing due to javascript's automatic semicolon insertion: Automatic semicolon insertion & return statements
If you try changing the position of the curly bracket from underneath to directly after the return statement, I think your problem will disappear.
// Filename: app.js
define(
.
.
.
function($, _, Backbone){
var initialize = function()
{
//initialize code here
}
return {
initialize: initialize
};
}
);

Categories