By eidias on (tags: javascript, sammy, categories: tools, web)

Another nice javascript lib that’s handy to have in your utility belt. From the library website - sammy is “a small web framework with class”. I’m sure there’s much more to it than what I will describe here, but there’s one aspect I’d like to focus on: view switching.

When building a SPA or another type of ‘front-end heavy’ app, there’s a matter of representing and switching between pages and subpages. You can parse the url along with anything that’s after the “#” (used so that the browser will not refresh the page after changing the url), but that’s just plain ol’ boring. Here’s how you do it with sammy:

   1: (function($) {
   3:     // define a new Sammy.Application bound to the #main element selector
   4:     Sammy('#main', function() { //#main is the container that will have it's content switched
   6:         // define a 'get' route that will be triggered at '#/:path'
   7:         this.get('#/:path', function() { // ":path" is sammys syntax for route parameters
   8:             var path = this.params['path']; // here's how you get the parameter value
  10:             // this context is a Sammy.EventContext
  11:             this.$element() // that is - $('#main')
  12:                 .html('A new route!'); // operations involving displaying your view go here
  13:         });
  14:     }).run();
  16: }(jQuery));

You need to make sure that this code is run after the DOM is ready – so preferably, at the end of your document.

jQuery is required.

This may not seem like much, but if you look at it closely it is very handy. The best comparison I can think of is that this serves the same purpose as the routing mechanism in It allows you to decouple your views from your routes and (what’s more important) switch them automatically. I love it.