I'm incorporating SignalR into a project where I'm already using require.js to handle my scripts dependencies.
I'm having a little trouble making sure "/signalr/hubs" is called after "jquery.signalR-1.1.2" loads.
I got it to work, but I'm wondering if there is a better alternative out there.
This is what I have:
require(["signalr"], function () {
require(["noext!/signalr/hubs"], function () {
//initialize and work with the hub here
}
}
Is there a way I can create a shim here to establish the dependency between signalr/hubs and the signalr script?
Thanks!
This works for me with SignalR 1.1.2:
require.config({
baseUrl: "/<your scripts dir>",
paths: {
"jquery": "jquery-<your jquery version>.min",
"signalr.core": "jquery.signalR-<your signalr version>.min",
"signalr.hubs": "/signalr/hubs?"
},
shim: {
"jquery": {
exports: "$"
},
"signalr.core": {
deps: ["jquery"],
exports: "$.connection"
},
"signalr.hubs": {
deps: ["signalr.core"],
}
}
});
require(["jquery", "signalr.hubs"],
function($)
{
var hubProxy = $.connection.myHub;
// ... go to town ...
});
Related
I am looking for a way to create and include a single script which will house all my Google Analytics event tracking code. There are various points in my application where I want to be able to track clicks and interaction and I would like to be able to have all these functions in a single file.
My problem is I can't find a suitable way of doing that with RequireJS, which my site uses.
This is an example of what I would have. I'd like to target an anchor with a class of resend and trigger a GA event.
Resend
Sure that is simple enough, but I don't want to have to require a module everywhere I want to do event tracking. Is this necessary or is there a clearer/cleaner way to do it? I should point out I don't want to include Google Analytics as there are many tutorials on how to do that and I am already doing that through the traditional way of having it in the footer - it's only GA event tracking code I want to include.
This is my requireJS config.js:
require = {
baseUrl: '/assets/js',
paths: {
// Amcharts.
'amcharts': '/assets/vendor/amcharts/dist/amcharts/amcharts',
'amcharts.funnel': '/assets/vendor/amcharts/dist/amcharts/funnel',
'amcharts.gauge': '/assets/vendor/amcharts/dist/amcharts/gauge',
bootstrap: '/assets/vendor/bootstrap/dist/js/bootstrap.min',
jquery: '/assets/vendor/jquery/dist/jquery.min',
jstz: '//cdnjs.cloudflare.com/ajax/libs/jstimezonedetect/1.0.4/jstz.min',
pwstrength: '/assets/vendor/pwstrength-bootstrap/dist/pwstrength-bootstrap-1.2.7.min',
},
shim: {
'amcharts.funnel': {
deps: [ 'amcharts' ],
exports: 'AmCharts',
init: function() {
AmCharts.isReady = true;
}
},
'amcharts.gauge': {
deps: [ 'amcharts' ],
exports: 'AmCharts',
init: function() {
AmCharts.isReady = true;
}
},
pwstrength: {
deps: [
'jquery'
]
},
bootstrap: {
deps: [
'jquery'
]
}
}
};
// Apply the urlArgs here for cache busting.
require.urlArgs = requireBase.urlArgs;
This is how I ended up configuring my RequireJS config.js.
require = {
baseUrl: '/assets/js',
paths: {
'gaEventTracking': '/assets/src/js/crmpicco/gaEventTracking',
},
shim: {
'gaEventTracking': {
deps: [
'jquery'
]
},
}
};
// Apply the urlArgs here for cache busting.
require.urlArgs = requireBase.urlArgs;
There then exists a gaEventTracking.js in the /assets/src/js/crmpicco directory.
I'm new to working with RequireJS, and am trying to figure out shimming 3rd-party, interdependent scripts. Specifically, I'm trying to get the Stanford Crypto scripts imported.
Basically, the suite is comprised of the core (jsbn.js, jsbn2.js, base64.js, rng.js, and prng4.js), a basic RSA script (rsa.js), and an extended RSA script (rsa2.js).
rsa.js defines the global variable-object RSAKey, and rsa2.js references it.
function RSAKey() {
this.n = null;
this.e = 0;
this.d = null;
this.p = null;
this.q = null;
this.dmp1 = null;
this.dmq1 = null;
this.coeff = null;
}
I've set up my shim in a way that I thought was correct, but I get the error "RSAKey is not defined" in rsa2.js. The following is my shim:
require.config({
paths: {
'jsbn': "../StanfordRSA/jsbn.js",
'jsbn2': "../StanfordRSA/jsbn2.js",
'base64': "../StanfordRSA/base64.js",
'rng': "../StanfordRSA/rng.js",
'prng4': "../StanfordRSA/prng4.js",
'rsa': "../StanfordRSA/rsa.js",
'rsa2': "../StanfordRSA/rsa2.js"
},
shim: {
'rsa': {
deps: ['jsbn', 'jsbn2', 'base64', 'rng', 'prng4'],
exports: "RSAKey"
},
'rsa2': {
deps: ['rsa']
}
}
});
My understanding, then, is that if I set 'rsa2' as a requirement in one of my RequireJS modules, it would look at the shim and see that rsa2 is dependent on rsa, which is dependent on the core and exports RSAKey...But that's not what's happening, and it seems like either rsa isn't loading, or it isn't loading correctly. (Please note that all of this works using raw script tags. I'm trying to convert an already existing, already functioning webapp to RequireJS)
Thoughts?
Your basic setup is correct, except for 2 things:
(really important!) You have to omit the .js extensions!!!
You probably have missed the exact dependencies between the scripts.
After some experimentation and reading the comments at the top of the scripts, the working configuration is:
require.config({
paths: {
'jsbn': "../StanfordRSA/jsbn",
'jsbn2': "../StanfordRSA/jsbn2",
'base64': "../StanfordRSA/base64",
'rng': "../StanfordRSA/rng",
'prng4': "../StanfordRSA/prng4",
'rsa': "../StanfordRSA/rsa",
'rsa2': "../StanfordRSA/rsa2"
},
shim: {
'rng': {
deps: ['prng4']
},
'jsbn2': {
deps: ['jsbn']
},
'rsa': {
deps: ['jsbn', 'rng'],
exports: 'RSAKey'
},
'rsa2': {
deps: ['rsa', 'jsbn2'],
exports: 'RSAKey'
}
}
});
Check out a plunk here.
I've started a new backbone, marionette and require project using version 2.2 (i previously worked with 1.8) It seems a lot has changed. I'm getting an error when the browser loads marionette:
Uncaught TypeError: Cannot read property 'ChildViewContainer' of undefined
This is my main.js file:
require.config({
baseURL: 'scripts',
paths: {
"jquery": "lib/jquery",
"underscore": "lib/underscore",
"backbone": "lib/backbone",
"marionette": 'lib/backbone.marionette',
"templates": "../templates",
"text": "lib/text"
},
shim: {
underscore: {
exports: '_'
},
backbone: {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
marionette: {
deps: ['jquery', 'underscore', 'backbone'],
exports: 'Marionette'
},
waitSeconds: 15
}
});
require([ "app", "marionette"], function(App, marionette) {
App.start();
});
And this is my app.js file:
define(["marionette", "router"], function (Marionette, AppRouter) {
var MyApp = Marionette.Application.extend({
initialize: function(options) {
console.log("options.container");
}
});
var MyApp = new MyApp({container: '#page'});
MyApp.addInitializer(function (options) {
MyApp.Router = new AppRouter();
Backbone.history.start();
});
// export the app from this module
return MyApp;
});
Just look at your backbone.js file. It's empty. Download backbone.js from http://backbonejs.org/ and replace it.
I just ran into this same issue myself. The issue was multiple instances of Marionette being included on the page. (i had errantly placed a script tag for marionette on the page from cdnjs, as well as trying to include the static file locally via require). removing the reference to the external JS file helped me...
I can't seem to figure out how to load Bootstrap via RequireJS. None of the examples that I found worked for me.
Here is my shim:
require.config({
// Sets the js folder as the base directory for all future relative paths
baseUrl: "./js",
urlArgs: "bust=" + (new Date()).getTime(),
waitSeconds: 200,
// 3rd party script alias names (Easier to type "jquery" than "libss/jquery, etc")
// probably a good idea to keep version numbers in the file names for updates checking
paths: {
// Core libsraries
// --------------
"jquery": "libs/jquery",
"underscore": "libs/lodash",
"backbone": "libs/backbone",
"marionette": "libs/backbone.marionette",
// Plugins
// -------
"bootstrap": "libs/plugins/bootstrap",
"text": "libs/plugins/text",
"responsiveSlides": "libs/plugins/responsiveslides.min",
'googlemaps': 'https://maps.googleapis.com/maps/api/js?key=AIzaSyDdqRFLz6trV6FkyjTuEm2k-Q2-MjZOByM&sensor=false',
// Application Folders
// -------------------
"collections": "app/collections",
"models": "app/models",
"routers": "app/routers",
"templates": "app/templates",
"views": "app/views",
"layouts": "app/layouts",
"configs": "app/config"
},
// Sets the configuration for your third party scripts that are not AMD compatible
shim: {
"responsiveSlides": ["jquery"],
"bootstrap": ["jquery"],
"backbone": {
// Depends on underscore/lodash and jQuery
"deps": ["underscore", "jquery"],
// Exports the global window.Backbone object
"exports": "Backbone"
},
"marionette": {
// Depends on underscore/lodash and jQuery
"deps": ["backbone", "underscore", "jquery"],
// Exports the global window.Backbone object
"exports": "Marionette"
},
'googlemaps': { 'exports': 'GoogleMaps' },
// Backbone.validateAll plugin that depends on Backbone
"backbone.validate": ["backbone"]
},
enforceDefine: true
});
and here is how I call Bootstrap:
define([
"jquery",
"underscore",
"backbone",
"marionette",
"collections/Navigations",
'bootstrap',
],
function($, _, Backbone, Marionette, Navigations, Bootstrap){
The error that I get is this:
Uncaught Error: No define call for bootstrap
Any ideas on how to get this resolved?
I found a working example here:
https://github.com/sudo-cm/requirejs-bootstrap-demo
I followed it to get my code to work.
According to that demo, especially app.js, you simply make a shim to catch Bootstrap's dependency on jQuery,
requirejs.config({
// pathsオプションの設定。"module/name": "path"を指定します。拡張子(.js)は指定しません。
paths: {
"jquery": "lib/jquery-1.8.3.min",
"jquery.bootstrap": "lib/bootstrap.min"
},
// shimオプションの設定。モジュール間の依存関係を定義します。
shim: {
"jquery.bootstrap": {
// jQueryに依存するのでpathsで設定した"module/name"を指定します。
deps: ["jquery"]
}
}
});
and then mark Bootstrap as a dependency of the app itself, so that it loads before app.js.
// require(["module/name", ...], function(params){ ... });
require(["jquery", "jquery.bootstrap"], function ($) {
$('#myModalButton').show();
});
Finally, since app.js is the data-main,
<script type="text/javascript" src="./assets/js/require.min.js" data-main="./assets/js/app.js"></script>
Bootstrap's JS is guaranteed to load before any application code.
Bootstrap lib does not return any object like jQuery, Underscore or Backbone: this script just modifies the jQuery object with the addition of new methods. So, if you want to use the Bootstrap library, you just have to add in the modules and use the jquery method as usual (without declarating Bootstrap like param, because the value is undefined):
define([
"jquery",
"underscore",
"backbone",
"marionette",
"collections/Navigations",
"bootstrap",
],
function($,_,Backbone,Marionette,Navigations){
$("#blabla").modal("show"); //Show a modal using Bootstrap, for instance
});
I found it was sufficient to add the following to my requirejs.config call (pseudocode):
requirejs.config({
...
shim: {
'bootstrap': {
deps: ['jquery']
}
}
});
I like to use Require.Js ORDER plugin, what it does? Simply loads all your Libraries in order, in this case you won't get any errors, ohh and bootstrap depends on jQuery, so we need to use shim in this case:
requirejs.config({
baseUrl: "./assets",
paths: {
order: '//requirejs.org/docs/release/1.0.5/minified/order',
jquery: 'http://code.jquery.com/jquery-2.1.0.min',
bootstrap: '//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min'
},
shim: {
'bootstrap': {
deps:['jquery']
}
}
});
require(['order!jquery', 'order!bootstrap'], function($) {
});
I am having difficulty trying to get signalr to work with requirejs. This is my code I have but I get the following error:
_Uncaught Error: SignalR: Error loading hubs. Ensure your hubs reference is correct, e.g. <script src='/signalr/hubs'></script>._
Code:
<script src="~/Scripts/jquery.signalR-1.0.0-rc2.js"></script>
<script src="~/signalr/hubs"></script>
<script type="text/javascript">
// requirejs configuration setup
requirejs.config({
baseUrl: '#string.Format("{0}://{1}{2}Scripts/modules", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"))', // this might need to change as it depends on the number of / in the url...?
paths: {
'jquery': '../jquery-1.9.0',
'bootstrap': '../bootstrap',
'knockout': '../knockout-2.2.1',
'noext': '../noext',
'sigr': '../jquery.signalR-1.0.0-rc2'
},
shim: {
"sigr": {
deps: ['jquery']
},
"noext!signalr/hubs": {
deps: ['sigr']
}
}
});
Does anyone have any ideas as to why or how I can get this to work?
I was able to get require to work with requirejs..I followed the tutorial on http://requirejs.org/docs/jquery.html on how to plugin jquery and added signal references for this to work
require(["jquery", "jquery.alpha", "jquery.beta","jquery.signalr-1.0.0-rc2","/signalr/hubs"],
function($) {
}
);
I think you have to modify your configuration to do either of the following
Option1:
paths: {
'jquery': '../jquery-1.9.0',
'bootstrap': '../bootstrap',
'knockout': '../knockout-2.2.1',
'noext': '../noext',
'sigr': '../jquery.signalR-1.0.0-rc2'
'hubs': '/signalr/hubs'
},
Option2:
shim: {
"sigr": {
deps: ['jquery']
},
"noext!**/**signalr/hubs": {
deps: ['sigr']
}
}