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
};
}
);
Related
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'}
}
})
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'
},
}
Instead of having one giant js file that has a whole bunch of "defines", how do I call my various "define" functions from other files?
I've been copying these examples, but still cannot get it to work:
example-multipage
example-multipage-shim
example-jquery-shim
Here is what I have so far:
main.js
require.config({
baseUrl: '',
paths: {
jquery: '../libraries/jquery-1.10.2.min',
simControlView: '../javascripts/simControlView'
}
});
require(['jquery','loadPage'], function( $,loadPage)
{
loadPage();
});
define('loadPage', ['jquery'], function($)
{
var simControlView = require(['./simControlView']);
return function()
{
simControlView.showSimControlView(); //having problem here
};
});
simControlView.js
define(['jquery'], function ($) {
return {
showSimControlView: function () {
console.log("Hi!!");
}
}
});
Here is the error that I'm getting:
Uncaught TypeError: Object function d(e,c,h){var
g,k;f.enableBuildCallback&&(c&&H(c))&&(c.__requireJsBuild=!0);if("string"===typeof
e){if(H(c))return v(A("requireargs", "Invalid require
call"),h);if(a&&s(N,e))return Ne;if(j.get)return
j.get(i,e,a,d);g=n(e,a,!1,!0);g=g.id;return!s(r,g)?v(A("notloaded",'Module
name "'+g+'" has not been loaded yet for context: '+b+(a?"":". Use
require([])"))):r[g]}K();i.nextTick(function(){K();k=q(n(null,a));k.skipMap=f.skipMap;k.init(e,c,h,{enabled:!0});C()});return
d} has no method 'showSimControlView'
See anything I'm doing wrong? Any help is appreciated!
Try moving all the dependencies to the dependency list you pass to define().
Also, the ordering may be important. I.e. the define() of a module may need to come before the require() that requires it (talking about the 'loadPage' module).
Also, if your paths config calls a module 'simControlView', then it needs to be referred to as 'simControlView', and not as './simControlView'.
E.g.:
define('loadPage', ['jquery', 'simControlView'], function($, simControlView) {
return function() {
simControlView.showSimControlView();
};
});
require(['jquery', 'loadPage'], function($, loadPage) {
loadPage();
});
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) {
});
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.