SammyJS and Mustache in ASP.NET - Short and Sweet

I recently started working with SammyJS in my investment tracking web app and thought others might get some value out of a blog post on the topic. I had already developed a basic app API and ASP.NET website, but wanted to add support for the Single Page App (SPA) model to facilitate mobile access.

At its core, SammyJS is a JavaScript framework which provides an event and routing subsystem for web apps using jQuery, AJAX, and desiring a structured client-side design. This fit my need and has integrated well so far.

Obviously, the first thing I needed to do was download the sammy.js JavaScript and save it to my project’s js folder. Alternatively, I could reference the file from a CDN. Although neither the Microsoft ASP.NET CDN nor Google CDN host Sammy yet, CloudFare has a large library of JavaScript, etc hosted by their CDNJS project - including Sammy!

1 //

Sammy is compatible with and uses jQuery, so if you haven’t already, you’ll need to include a reference to jQuery (v1.4.1 or above) also (be sure to add the reference to jQuery above Sammy).

1 <script src=""> </script> 
2 <script src="./Scripts/sammy-latest.min.js"> </script>

And that’s it! Well, almost.

I include my references to Mustache and the SammyJS plugin for Mustache also. All Sammy Plugins can be found in the Sammy repositiory on Github.

Much like RequireJS, Sammy needs a “main” or app specific JavaScript segment best implemented in a separate js file. I called mine sammy-app.js for simplicity.

1 <script src=""> </script> 
2 <script src="./Scripts/sammy-latest.min.js"> </script> 
3 <script src="./Scripts/mustache.js"> </script> 
4 <script src="./Scripts/sammy.mustache.js"> </script> 
5 <script src="./Scripts/sammy-app.js"> </script>

Inside the sammy-app.js goes our single page routing logic. I prefer to use the module pattern for my variables (thanks to Eric Miraglia (@miraglia), for this!), so first you see the “MyGlobalVar” definition. This is not required by Sammy, but I think it is useful so I have retained it here. Also, within the Sammy instantiation, you’ll find my reference to Mustache which tells Sammy to fetch and use the Mustache engine for templates.

 1 // First, my global variable - not required nor used by Sammy 
 2 var MyGlobalVar = (function () { 
 4 	var my = {}; 
 6 	// Publics 
 7 	my.SammyApp = null; 
 8 	// ... Other missing properties and functions 
10 	// Return 
11 	return my; 
13 } ()); 
15 // Now, the SammyJS-specific code wrapped inside a DOM-ready global function. 
16  (function ($) { 
18 	MyGlobalVar.SammyApp = $.sammy('#sammyMain', function () { 
20 	// Reference Mustache for templating functionality 
21 	this.use('Mustache'); 
23 	////////////////////////////////////////////////////////////// 
24 	// Root - Main 'homepage' of SPA 
25 	this.get('#/', function (context) { 
27 		context.log('Sam-Main'); 
29 		// Load the User's Financial Asset table template 
30 		MyGlobalApp.SammyApp.swap(''); 
31 		this.render('/Sam/Tmpl/UserFinAssetTable.mustache', { item: 'dummy' }).appendTo(context.$element()); 
33 		// Load the data rows and populate the table 
34 		this.load(MyGlobalApp.Ajax_GetUserFinAssets, { json: true, cache: false }).then(function (items) { 
36 			 $.each(items, function (i, item) { 
38 				context.log("Ticker: " + item.FinancialAsset.TickerSymbol + "; Shares: " + item.Shares + "; Balance: " + item.Balance); 
40 				item.Shares = MyGlobalApp.FormatNumber(item.Shares);
41 				item.Balance = MyGlobalApp.FormatCurrency("$ {n}", item.Balance); 
43 				context.render('/Sam/Tmpl/UserFinAssetRow.mustache', item).appendTo('#userFinancialAssets');
45 			}); 
46 		}); 
47 	}); 
48 });

How does Sammy know where to insert changes into the DOM? When instantiating the Sammy instance, I’ve specified “#sammyMain” as a parameter. This parameter tells Sammy what node in the DOM is the outer node of it’s primary update region.

1 MyGlobalVar.SammyApp = $.sammy('#sammyMain', function () {

In this case my ASP.NET ASPX page is very small. It includes the SCRIPT tags previously mentioned, along with a DIV tag with the “#sammyMain” id, all wrapped in the ASP.NET Content node.

1 <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> 
2 <div id="#sammyMain"> 
3 </div> 
4 <script src=""> </script> 
5 <script src="./Scripts/sammy-latest.min.js"> </script> 
6 <script src="./Scripts/mustache.js"> </script> 
7 <script src="./Scripts/sammy.mustache.js"> </script> 
8 <script src="./Scripts/sammy-app.js"> </script> 
9 </asp:Content>

Moving along, I tell Sammy about my “root” route in the call to the get method and specify the handler for the associated event. This get method/handler pattern can be repeated for any number of additional routes you might need.

1 // Root - Main 'homepage' of SPA 
2 this.get('#/', function (context) {

First, I log to help with debugging, then call Sammy’s swap method. This isn’t important at first, but when you have more than one route, and your user returns to the “root” route, the swap call ensures the content is cleared before new content is rendered. The next line of code brings in the Mustache template for my main grid. For the most part, this Mustache template is just a placeholder for the results of the row template that comes a couple of lines later.

 1 // Load the User's Financial Asset table template 
 2 MyGlobalApp.SammyApp.swap(''); 
 3 this.render('/Sam/Tmpl/UserFinAssetTable.mustache', { item: 'dummy' }).appendTo(context.$element()); 
 5 // Load the data rows and populate the table 
 6 this.load(MyGlobalApp.Ajax_GetUserFinAssets, { json: true, cache: false }).then(function (items) { 
 8 	$.each(items, function (i, item) { 
10 		context.log("Ticker: " + item.FinancialAsset.TickerSymbol + "; Shares: " + item.Shares + "; Balance: " + item.Balance); 
12 		item.Shares = MyGlobalApp.FormatNumber(item.Shares);
13 		item.Balance = MyGlobalApp.FormatCurrency("$ {n}", item.Balance); 
15 		context.render('/Sam/Tmpl/UserFinAssetRow.mustache', item).appendTo('#userFinancialAssets');
16 	}); 
17 });

Here are the Mustache templates, so you can see how it fits together. First the UserFinAssetTable.mustache template:

1 <table id="userFinancialAssets">
2 	<tr>
3 		<th>Ticker</th> 
4 		<th>Shares</th> 
5 		<th>Balance</th> 
6 	</tr> 
7 </table>

Next, the UserFinAssetRow.mustache template:

1 <tr>
2 	<td>
3 		<a href="../FinAsset/?ts={{FinancialAsset.TickerSymbol}}">{{FinancialAsset.TickerSymbol}}<a> 
4 	</td> 
5 	<td>{{Shares}}</td>
6 	<td>{{Balance}}</td> 
7 </tr>

Admittedly, I don’t go into depth on Sammy here, but I hope the examples and explanation I have provided will help others who are starting out with SammyJS and Mustache.

Thanks for reading!

Daniel (@dwdii)