Single Page Apps – Loading JSON Using Sammy

Sammy.jsSingle Page Applications (SPA) are web sites/applications which are consists of single page and provide smooth user experience in contrast with traditional click and refresh web pages. You can integrate data loading along with routing to provide your users with a site or app that “pops”. No waiting, because the data has already been loaded.

We will start with a prototype for a Sammy page, which provides a div whose identifier is main, where we will render the data. And the code to load the scripts.

This tutorial refers to version 0.7.4 of Sammy.

Getting Started

While you would normally put the script into an app.js file, I will include the application script on the page itself, so you can easily see how the app fits together.

The Data

Put the following data into a folder named Data, in a file named products.txt.

Loading Data

Sammy has around() that you use to get the data for the page. Use is used to make asynchronous request to the server/filesystem and then when its complete, you can choose to move on to the route or not. Around is called whenever the route is run, and to continue the route, you need to execute its callback parameter, otherwise, the route will be effectively cancelled.

The intent of around() is for calling a function that could be asynchronous, and executing the route within the function’s callback.

When the call is completed, instead of just proceeding to the route, we have to let Sammy know to move on to the next operation.

Our data loading call will look like this:

In this case, you are calling Sammy’s EventContest method load(), which automatically checks to see if the file extension to the filename is .json, and if so, treats the file as json.

Calling JSON As a Text File

But what happens when you are using a .txt file to serve your JSON? When Sammy loads the data, if it finds an extension that is not .json, it will load the data as text. And you will not retrieve the data as a JavaScript variable.

Other Options

Note that the data is cached by default in sammy’s templateCache(). But you can turn off the cache by setting that option to false.

Then

Note: the .then method for load is not part of a promise, meaning that when you use sammy.load() you will need to extend load to handle loading failures.

Sample Loading JSON Data Using Sammy

Sample Code

You can get the sample code for this post in the DevDays repository on GitHub:  https://github.com/devdays/single-page-app/tree/master/Sammy 

References

Sammy API reference

Sammy Source Code

Single page application in asp.net using Sammy.js

Advertisements

One comment

  1. Pingback: Single Page Apps – Deep Dive into Loading Templates Using Sammy, Mustache, RequireJS | DevDays®