Single Page Apps – Local Data Store with AmplifyJS

imageYou may want to use storage to store data. You can save the data your user has entered in a wizard. Or you might want to save data so you can provide an offline experience. Or you may want to store user preferences. Local storage is a good idea anytime you do not want, or need your user or your application to start all over.

AmplifyJS is a very neat library that provides a consistent API to handle client storage that works in most browsers.

Of course, you can use HTML5 Local Storage. But amplify.store supports IE 5+, Firefox 2+, Safari 4+, Chrome, Opera 10.5+, iPhone 2+, Android 2+ and provides a consistent API to handle storage cross-browser.

Note: Because of the JSON dependency, you need to add json2.js for support in browsers without native JSON support, including IE 5, IE 6, IE 7, Firefox 2.0 and Firefox 3.0.

Publish/subscribe and store components do not use jQuery at all. You will need jQuery for Amplify Request that you can learn about in a later post.

About AmplifyJS

amplify.store is lets you use the latest storage technologies for those browsers that have them, while gracefully degrading for those without support. You can specify the storage technology you want to use, or amplify.store will use feature detection to select the right one.

amplify.store also handles serializing to and from a JavaScript object using JSON serialization where necessary.

Support for the following storage types are built into amplify.store and are detected in the order listed. The first available storage type will become the default storage type when using amplify.store().

localStorage
  • IE 8+
  • Firefox 3.5+
  • Safari 4+
  • Chrome
  • Opera 10.5+
  • iPhone 2+
  • Android 2+
sessionStorage
  • IE 8+
  • Firefox 2+
  • Safari 4+
  • Chrome
  • Opera 10.5+
  • iPhone 2+
  • Android 2+
globalStorage
  • Firefox 2+
userData
  • IE 5 – 7
    • userData exists in newer versions of IE as well, but due to quirks in IE 9’s implementation, we don’t register userData if localStorage is supported.

memory

An in-memory store is provided as a fallback if none of the other storage types are available.

Getting Started with AmplifyJS

You can get the latest version from AmplifyJS Website.Click the Download button.

You can also get the source from Amplify on GitHub.

Or you can get AmplifyJS for your Visual Studio application using NuGet.

image

Amplify Store Code

It’s pretty easy to use AmplifyJs on your site. After adding the appropriate script references, you can use amplify like this:

var product = { name: "My Cookie Dough" };
amplify.store( "storeProduct1", product );

The value storeProduct1 is the key that the item is stored. You retrieve the value as follows:

var item = amplify.store( "storeProduct1" );

Ways to Store

You can put value that can be serialized as JSON into the Amplify store, such as a key value pair or a key and a variable that is Amplify will serialize for you.

You can use Amplify to store your data using a key value pair.

// you can store a simple data value
amplify.store("product", "Bolt cutter");

// and then retrieve it using its key
var myProduct = amplify.store("product");
$("#product").text("product of the day is " + myProduct);

You can use Amplify to store a more complex value and later get that value.

var product = {
  name: "My Cookie Dough",
  size: "24 oz"
};

// store the product in local storage or cookie
amplify.store("storeProduct1", product);

// now retrive the product using the key
var item = amplify.store("storeProduct1");
$("#dough").text(item.name + " available in " + item.size + ".");

Local Store Sample

The following code takes a first and last name entered by the user. When the user presses Store, Amplify stores the data into local storage or session, depending on the browser. When you press F5, the browser updates the placeholder attributes in the input with the stored data.


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Persist on Local Store</title>
</head>
<body>
<h3>Save My Name</h3>
<label for='firstName'>First Name:</label>
<div class='input'><input type='text' id='firstName' /></div>
<label for='lastName'>Last Name:</label>
<div class='input'><input type='text' id='lastName' /></div>
<input id="storeMe" type="button" value="Store" />
<script src="Scripts/jquery-1.4.4.js"></script>
<script src="Scripts/amplify.js"></script>
<script>
var myName = { firstName: "", lastName: "" };
$(function () {
aName = amplify.store("name");
if (typeof aName !== 'undefined') {
myName = aName;
$("#firstName").attr("placeholder", myName.firstName);
$("#lastName").attr("placeholder", myName.lastName);
} else {
$("#firstName").attr("placeholder","John")
$("#lastName").attr("placeholder","Jones");
}
});
$("#storeMe").click(function () {
myName.firstName = $("#firstName").val();
myName.lastName = $("#lastName").val();
amplify.store("name", myName);
});
</script>
</body>
</html>

Sample Code

You can find sample code for Amplify JS in the DevDays repository on GitHub. See https://github.com/devdays/single-page-app/tree/master/Amplify

Other Features in Amplify

The AmplifyJS core library provides two methods (amplify.publish and amplify.subscribe). AmplifyJS provides methods to facilitate the Publish and Subscribe messaging pattern in your front-end application. The idea is that someone is broadcasting one or more messages (publishing) and someone else is listening to one or more messages (subscribing). By separating your logic out like this it allows for loose coupling of your components, which results in less brittle and more reusable code.

References