Snippet – Fixing Errors When Using jQuery, Sammy, RequireJS

Sammy.jsWhile I was trying out Sammy.js with Require.js I kept getting several errors, among them:

  • jQuery is not defined
  • Uncaught TypeError: Object function ( selector, context ) { // The jQuery object is actually just the init constructor ‘enhanced’ return new jQuery.fn.init( selector, context, rootjQuery ); } has no method ‘sammy’

Here’s a code sample that shows how you can get the two to work together.

Sammy Config

The first trick was to create a shim for Sammy in the require.config. As of 0.7.4, Sammy does not define itself, although it does define itself as an AMD Anonymous Module requiring jquery. But for my app, jQuery and Sammy need to be loaded by RequireJS. So you can use a shim.

If you do not express the dependencies, you will likely get loading errors since RequireJS loads scripts asynchronously and out of order for speed.


shim: {
// we get an error that "jQuery is not defined" error without this
// shim for sammy
"sammy": {
deps: ["jquery"],
exports: "sammy"
}
}

jQuery Require is Optional

You can then require SammyJS in your require statement without needing jQuery. $ is already loaded as a dependency.

Note that you do not call $.sammy to when


require(['sammy'], function (sammy) {
var app = sammy('#content', function () {
this.get('#/', function (context) {
context.log('Yo yo yo');
});
this.get('#/:items', function (context) {
context.log('Ho ho ho');
});
});
$(function () {
app.run('#/');
});
})();

Sample Page

Here’s the complete sample. Sammy, Require, and jQuery are all in the Scripts folder.


<!DOCTYPE html>
<html>
<head>
<title>RequireJS and SammyJS</title>
</head>
<body>
<nav>
<ul>
<li><a href="#/">Items</a></li>
<li><a href="#/3">3</a></li>
</ul>
</nav>
<div id='content'></div>
<script src="Scripts/require.js"></script>
<script>
// ====== set up require.js ================
(function () {
"use strict";
require.config({
baseUrl: 'Scripts',
paths: {
"jquery": "jquery-1.9.1",
"sammy": "sammy-0.7.4",
},
shim: {
// we get an error that "jQuery is not defined" error without this
// shim for sammy
"sammy": {
deps: ["jquery"],
exports: "sammy"
}
}
});
})();
require(['sammy'], function (sammy) {
"use strict";
console.log("initializing sammy");
var app = $.sammy('#content', function () {
this.get('#/', function (context) {
context.log('Yo yo yo');
});
this.get('#/:item', function (context) {
var param = this.params['item'];
context.log('Ho ho ho ' + param);
});
});
$(function () {
app.run('#/');
});
//})();
</script>
</body>
</html>

Sample Code

Sample Code for this is available in the DevDays repository on GitHub: https://github.com/devdays/single-page-app/tree/master/Sammy