Our Story

Ceremony

Just Married

Sammy.JS

by - November 30, 2010

I’ve been looking at Sammy.JS recently. It’s a lightweight Javascript framework for managing transitions on your page. It extends jQuery. The neat trick it uses is to leverage the anchor part of the URI – that’s the bit after the ‘#’ to provide routes into your javascript. If you’ve used the new routing framework in ASP.NET you’ll understand it straight away.

Here’s a quick example I’ve put together. We’ve got three links with three paragraphs. As you click the links the related paragraph appears.

This is the first paragraph.

This is the second paragraph.

This is the third paragraph.

The big deal is that I now have a URI to each paragraph and normal browser functions like the back button work. Go on, you can try it. I can correctly link straight to a particular state of my Ajax application, and you know what a PITA that can be.

Here’s the code for the page:

<html>
<head>
<title>Sammy Test</title>
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="sammy.js" type="text/javascript"></script>
<script src="sammy_test.js" type="text/javascript"></script>
</head>
<body>
<div id="header">
<h1>Sammy Test</h1>
<a href="#/one">one</a>
<a href="#/two">two</a>
<a href="#/three">three</a>
</div>
<div id="main">
<p id="one">This is the first paragraph.</p>
<p id="two">This is the second paragraph.</p>
<p id="three">This is the third paragraph.</p>
</div>
</body>
</html>





And here’s the script:




(function($) {

var app = $.sammy('#main', function() {

var hideAll = function() {
$("#one").hide();
$("#two").hide();
$("#three").hide();
};

this.get('#/', function(context) {
hideAll();
});

this.get("#/one", function(context) {
hideAll();
$("#one").show();
});

this.get("#/two", function(context) {
hideAll();
$("#two").show();
});

this.get("#/three", function(context) {
hideAll();
$("#three").show();
});
});

$(function() {
app.run('#/');
});

})(jQuery);





If you are writing even a slightly complicated Ajax application it’s worth checking Sammy out.

You May Also Like

0 comments