Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Single Page App - Sammy with RequireJS
<!DOCTYPE html>
<html>
<head>
<title>Sammy+Mustache+RequireJS</title>
</head>
<body>
<nav>
<ul>
<li><a href="#/">Home</a></li>
<li><a href="#/products">Products</a></li>
<li><a href="#/products/1">Product 1</a></li>
<li><a href="#/data">Data</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: {
//"underscore": "lodash",
"jquery": "jquery-1.9.1",
//"q": "q",
"sammy": "sammy-0.7.4",
"mustache": "mustache",
"mustachePlugin" : "sammy.mustache"
},
shim: {
// we get an error that "jQuery is not defined" error without this
// shim for sammy
"sammy": {
deps: ["jquery"],
exports: "sammy"
}
}
});
})();
require(['sammy', 'mustachePlugin'], function (sammy) {
"use strict";
var app = sammy('#content', function () {
// first param is a function name
this.use('Mustache', 'html');
// the callback is the entire route wrapped in a closure
this.around(function (callback) {
var context = this;
this.load('data/3-products.txt', { json: true })
.then(function (items) {
context.items = items;
})
.then(callback);
});
this.get('#/', function (context) {
context.app.swap('');
context.$element().append('<h1>Main page</h1>');
});
this.get('#/data', function (context) {
context.app.swap('');
context.$element().append(JSON.stringify(context.items));
});
this.get('#/products/:id', function (context) {
var param = context.params['id'];
var products = context.items.products;
if (!products[param]) {
return context.notFound();
}
// partial() internally calls render and swap
// creates the html and puts it into $element
context.partial('Templates/productDetail.html', products[param]);
});
this.get('#/products', function (context) {
var products = context.items;
context.app.swap('');
context.render('templates/productsList.html', products)
.appendTo(context.$element());
});
});
$(function () {
app.run('#/');
});
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment