¶ Edit

X Delete


7 years ago

Persistent Storage

Storing data is easy! Just assign properties to the global object storage, and they'll stick around.

Here we'll show you some storage examples, or you can skip directly to the reference page on storage.

Here's how to make a hit counter.


if (!storage.count) {
    storage.count = 0;
storage.count += 1;

printp("I count ",storage.count, " hits.");

page.setTitle("Hit me baby one more time");

You can store primitive values and Dates this way. You can also store JavaScript objects, which are automatically converted to StorableObjects. StorableObjects are special objects that are persisted between requests to your app. Their main restriction is that they can't have function properties.

Here is an example that lets the user vote for their favorite Simpson, and shows poll results. The "storage model" is just an object storage.pollResults with a property for each Simpson.


if (! storage.pollResults) {
    storage.pollResults = {
        Homer: 0, Marge: 0, Bart: 0, Lisa: 0, Maggie: 0,
        Jessica: 0, 'O.J.': 0 }

function post_vote() {
    for(simpsonName in storage.pollResults) {
        if (request.params[simpsonName]) {
            storage.pollResults[simpsonName] += 1;

function get_main() {
    page.setTitle("Simpsons Poll");
    print(H3("Who is your favorite Simpson?"));

        function(simpsonName, currentCount) {
            var theButton =
                INPUT({type:"submit", name:simpsonName, value:"Vote!"});
               theButton," ",currentCount," - ",simpsonName));


To elaborate on how this works: Each button gets its own HTML form, and the button itself serves as a form parameter as well as submitting the form. The form posts to path /vote, which tallies it and redirects back to the original page. Redirection is the recommended way to do this (i.e. to take an action that modifies state, then go back to displaying it).

To read about how to store collections of objects (analogous to a database table), see StorableCollections.

Further Notes:

  • Functions and some other kinds of JavaScript objects can't (currently) be stored. Because of this, StorageObjects cannot have methods, and objects with methods cannot be coerced. These rules prevent objects from breaking unexpectedly when persisted.

  • Mutual and recursive references in StorageObjects and coerced objects are allowed, i.e. you can have arbitrary object graphs.

  • The global variable storage gives you access to the "root" StorageObject, which cannot be replaced. StorageObjects that aren't reachable from the root at the end of your program are lost.

Powered by AppJet on JGate
rendered in 0.109s