I load require.js with jQuery included like this in my html:
<script data-main="requires" src="lib/require-jquery.js"></script>
The content of my requires.js:
require.config( {
paths: {
"jquery.mobile": "lib/jquery.mobile",
"jquery.mobile.router": "lib/jquery.mobile.router"
},
shim: {
"jquery.mobile" : {
"exports": "$.mobile"
},
"jquery.mobile.router": {
"deps": [ "jquery.mobile" ],
"exports": "$.mobile.Router"
}
}
} );
require(["jquery.mobile.router" ], function() {
require(["router"]);
} );
And in my router.js i create a new instance of the jquery mobile router plugin:
router = new $.mobile.Router(...);
Which gives me this error:
Uncaught TypeError: undefined is not a function
When I output $ and $.mobile, they are both defined, just $.mobile.Router is undefined.
What have I done wrong here?
My Problem was that I added jquery.mobile as a dependency for jquery.mobile.router, thus jQuery mobile will be loaded first, where as the documentation for the router states this:
The jQuery Mobile router javascript file must be loaded before jQuery Mobile.
This is how I changed my requires.js to fix the problem:
require.config( {
paths: {
"jquery.mobile": "lib/jquery.mobile",
"jquery.mobile.router": "lib/jquery.mobile.router"
},
shim: {
"router": {
"deps" : ["jquery.mobile"]
},
"jquery.mobile" : {
"deps" : [ "jquery.mobile.router"],
"exports": "$.mobile"
},
"jquery.mobile.router": {
"exports": "$.mobile.Router"
}
}
});
require(["router"]);
Now I just require my router.js and load jquery.mobile and jquery.mobile.router as dependencies. Load order now is this:
jquery.mobile.router
jquery.mobile
router
Try this in your router.js file:-
define(["jquery", "jquery.mobile.router"], function($) {
// your js code in router.js
} );
By specifying jquery in your define call and passing in $ as an argument, the jquery object $ and associated functions defined in jquery.mobile.router are now made available in the scope of your code (contained in the file router.js in its entirety).
Related
I am using the Stripe library and I've got a vue component that is dependent on the library being loaded first.
I found RequireJS (2.3.6) and having never used it, am just wondering if I'm doing things correctly
I trie using the answer in this question but I can't get it working Load Stripe.js with Require.js
requirejs.config({
paths: {
'stripe': 'https://js.stripe.com/v3/'
},
shim: {
'stripe': {
exports: 'Stripe',
deps:['my-component.js']
}
}
});
I don't get any console errors but I don't see my component either
I worked it out in the end
requirejs.config({
shim: {
form: {
deps: [ 'stripe' ]
}
},
paths: {
stripe: 'https://js.stripe.com/v3/?noext',
form: '/js/my-component'
}
});
require(['stripe', 'form'], function($) {
return {};
});
I am new working with requirejs, I have an old Asp.net Webform application that I am trying to apply some javascript module loading using requirejs. In this app I am using a jquery plugin named Time Entry, but is not working if I use requirejs, only works if I added the reference the old way. Here is my requirejs configuration and declaration.
In the aspx file:
<script src="../../scripts/require.js"></script>
<script>
require(["../../app/shared/require.config"],
function (config) {
require(["appIncidentTracking/incident-type-init"]);
});
</script>
My require.config file is like this:
require.config({
baseUrl: '../../scripts',
paths: {
app: '../../app/utilization-management',
appIncidentTracking: '../../app/incident-tracking',
jquery: 'jquery-3.1.1.min',
jqueryui: 'jquery-ui-1.12.1.min',
jqueryplugin: '../../js/jquery.plugin.min',
timeentry:'../../js/jquery.timeentry.min',
handlebars: 'handlebars.amd.min',
text: 'text',
moment: 'moment.min',
datatable: 'DataTables/jquery.dataTables.min',
blockUI: 'jquery.blockUI.min',
shared: '../../app/shared',
bootstrap: 'bootstrap.min',
'bootstrap-datepicker': 'bootstrap-datepicker.min',
'bootstrap-multiselect': '../js/bootstrap-multiselect/bootstrap-multiselect'
},
shim: {
bootstrap: {
deps: ['jquery']
},
'bootstrap-multiselect': {
deps: ['bootstrap']
},
timeentry: {
deps:['jquery', 'jqueryplugin']
}
}
});
and in my incident-type-init.js I only call the plugin:
/**
* Incident Type Init page
* #module incident-type-init
*/
define(function (require) {
var $ = require('jquery'),
jqueryplugin = require('jqueryplugin'),
timeentry = require('timeentry'),
bootstrap = require('bootstrap');
/**
* Jquery ready function
*/
$(function () {
$('.js-timeentry').timeEntry();
});
});
but when the application runs I got this error:
$.JQPlugin.createPlugin is not a function, it is like does not find the jquery.plugin.js
I checked the network tab in chrome and both files are loaded, jquery.plugin.js and jquery.timeentry.js
UPDATE: In our application, we are using Asp.net MasterPages, and there we are loading an old jquery version, 1.5.1, and I use that MasterPage in my page, but when I check the network tab in chrome, is loading the MasterPage scripts first,then all the requirejs stuff.
and the funniest part is that sometimes work, sometimes not.
Any clue?
The module jqueryplugin needs to have jQuery already loaded for it. It is not an AMD module because it does not call define. So you need an additional entry in shim for it:
jqueryplugin: ["jquery"]
The above is short for:
jqueryplugin: {
deps: ["jquery"]
}
I don't think your code is syntactically correct.
Try this:
1. Your script should refer to the require.config in data-main.
<script data-main="PATH_TO_CONFIG_FILE" src="../../scripts/require.js"></script>
2. Quotes are missing in paths of the config file. Instead it should be like this
require.config({
baseUrl: '../../scripts',
paths: {
"app": '../../app/utilization-management',
"appIncidentTracking": '../../app/incident-tracking',
"jquery": 'jquery-3.1.1.min',
"jqueryui": 'jquery-ui-1.12.1.min',
"jqueryplugin": '../../js/jquery.plugin.min',
"timeentry":'../../js/jquery.timeentry.min',
"handlebars": 'handlebars.amd.min',
"text": 'text',
"moment": 'moment.min',
"datatable": 'DataTables/jquery.dataTables.min',
"blockUI": 'jquery.blockUI.min',
"shared": '../../app/shared',
"bootstrap": 'bootstrap.min',
"bootstrap-datepicker": 'bootstrap-datepicker.min',
"bootstrap-multiselect": '../js/bootstrap-multiselect/bootstrap-multiselect'
},
shim: {
"bootstrap": {
deps: ["jquery"]
},
"bootstrap-multiselect": {
deps: ["bootstrap"]
},
"timeentry": {
deps:["jquery", "jqueryplugin"],
exports:"timeentry"
}
}
});
3. Since your module has dependencies, list them like this:
define(["jqueryplugin","timeentry","bootstrap"],function(jqueryplugin,timeentry,bootstrap) {
$(function () {
$('.js-timeentry').timeentry();
});
});
I keep getting:
Uncaught TypeError: object is not a function
The first time:
<script>
require(['core/controller']);
</script>
The secondoccurrence is:
require.config({
paths: {
"jquery": [
"jquery"
],
'bootstrap': [
'bootstrap'
],
'kendo': [
'kendo'
],
handlebars: 'handlebars'
},
shim: {
"bootstrap": {
deps :["jquery"]
},
"kendo": {
deps: ["jquery"]
}
}
})
define('config', function (require) {
'use strict';
var module = require('module');
return module.config ? module.config() : {};
});
define('events', ['core/mini-events'], function(EventEmitter){
var events = new EventEmitter();
return events;
});
In my header I have:
<script data-main="/js/main.js" src="http://mbms.com/js/requirejs.js"></script>
<script data-main="/js/main.js" src="http://mbms.com/js/requirejs.js"></script>
The absolute URL that you mentioned in your script's src doesn't exist. As the host and the file do not exist, requirejs.js is not downloaded and any attempt to use require API will give you the error that you're getting now. As you're running this locally, I suggest you change your src like below
<script data-main="/js/main.js" src="/js/requirejs.js"></script>
As long as there's a js folder with requirejs.js file under your project root folder, then this change should work :)
[EDIT for clarity]
I tried the URL referenced in the script tag just now and it's not present. Check your debugger's Network console and you'll see the 404. Perhaps you meant:
http://requirejs.org/docs/release/2.1.16/minified/require.js
I have kind of the same problem described in this question but there seem to be no right answer.
I'm trying to load the "loadImages" lib with require.js but I get this
Uncaught TypeError: Object [object Object] has no method 'imagesLoaded'
Here is the script on my page :
require(['./js/common'], function(common)
{
require(['home/main-home']);
});
My common.js
requirejs.config({
baseUrl: './js',
paths: {
jquery : 'libs/jquery/jquery-2.0.3.min',
eventie : 'libs/eventie/eventie',
eventEmitter : 'libs/eventEmitter/eventEmitter.min',
imagesLoaded : 'libs/imagesLoaded/imagesloaded.pkgd.min',
masonry : 'libs/masonry/masonry.pkgd.min',
wall : './wall/wall',
underscore : '../libs/underscore/underscore-min',
backbone : '../libs/backbone/backbone-min',
},
shim: {
jquery : {
exports : '$'
},
imagesLoaded : {
deps : ['jquery', 'eventie', 'eventEmitter']
},
masonry : ['jquery'],
wall : ['masonry', 'imagesLoaded'],
backbone : {
deps : ['jquery', 'underscore'],
exports : 'Backbone'
},
underscore : {
exports : '_'
}
}
});
and this is my main-home.js where I want to use the imagesLoaded lib.
define([
'wall'
],
function(Wall){
$(function()
{
$('#photos').imagesLoaded( function(){}); // ERROR
});
return true;
});
In the imagesLoaded doc there's a small paragrah about require.js which i don't really understand. I tried to load thoses libs as well, but it is not changing anything.
// Install imagesLoaded and its dependencies
// Update your RequireJS paths config so it can find those modules
requirejs.config({
paths: {
"eventie": "bower_components/eventie",
"eventEmitter": "bower_components/eventEmitter"
}
});
They seem to talk about it in here https://github.com/desandro/imagesloaded/issues/68, but I don't really know what to do.
Here is the js files my page is loading :
We can see that imagesLoaded is loaded...
How come do I still have this error then ?
This jsfiddle works.
I've edited the ImagesLoaded JS (as a gist) to give the modules a valid module id.
Search for:
// --------------------------------------------------
// ADDED A MODULE ID
// --------------------------------------------------
in the code for the 3 changes (to define the imagesLoaded, eventEmitter/EventEmitter and eventie/eventie modules).
Given that the ImageLoaded JS file already includes the other 2 modules, there is no need for any more paths/shims.
HTML
<div id="photos"></div>
<script>
require = {
paths: {
"jquery": "http://code.jquery.com/jquery-2.0.3",
"imagesLoaded": "https://rawgithub.com/gitgrimbo/6451492/raw/f26e23d7a180ee23fd3dea3b0b152dbf523854a1/ImageLoaded-mod"
}
};
</script>
<script src="http://requirejs.org/docs/release/2.1.8/comments/require.js"></script>
JS
require(["jquery", "imagesLoaded"], function($, imagesLoaded) {
console.log($.fn.jquery);
console.log(imagesLoaded);
$('#photos').imagesLoaded(function() {
console.log("something");
});
});
Output
2.0.3
ImagesLoaded( elem, options, onAlways )
something
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
};
}
);