Working with Client-Side Storage Using datajs Store API
One of the interesting features that datajs library includes is a store API which abstract the use of client-side storage mechanisms. You can use the store API in order to have a storage layer in your client-side and therefore reduce the calls for the server. Since datajs is only in alpha then this API might change in the future but even so I’ll explain and show a how to use it in this post.
datajs Storage Options
datajs currently provides an abstraction layer on top of the following three client-side storage options:
- In-memory – the datajs team implemented an in memory storage mechanism that can be used with the datajs library.
- DOM Storage – I wrote about this client storage type in the past. Most of the new browsers (IE, Chrome, Firefox, Opera and more) include implementation for DOM Storage which is a key-value dictionary that exists on client-side.
- IndexedDB – this is a new HTML5 specification that is being developed these days and therefore it is only experimental. Most of the browsers haven’t implemented this feature yet. Even so, datajs team is exploring this option and when the browsers will provide IndexedDB implementation you’ll be able to use it through datajs.
datajs Store API
The first thing that you’ll want to do when you use the store API is to create the storage object. In order to do that you will have to call the createStore function. The function gets two parameters – the name of the storage and the mechanism to use underneath. The mechanism parameter is optional and can get one of the following options:
- best – datajs will use the modern API that exists in the user’s browser. This is the default value so if you won’t provide a value to the mechanism parameter datajs will choose the best option for you.
- memory – datajs will use the in-memory implementation that is provided in the library.
- dom – datajs will use the Dom Storage implementation.
- indexeddb – datajs will use the IndexedDB implementation.
Here an example of creating a new storage object that uses Dom Storage:
After you have created the store object you can start using the store API. The API includes many simple functions such as add, remove, update, lookup and more. For further reading about those methods go to store API page. One of the things that you will notice about the API is that all the API functions work asynchronously (they get success and error callbacks).
datajs Store API Example
Lets look at a simple example:
In this post I gave you a simple taste of datajs’s store API. If this is something that interests you the datajs team looks for feedback about their decisions. Some of their questions are written in the store API page.