Search code examples
titaniumrequirecartcommonjs

How to store app-wide variables when using CommonJS?


I am developing apps using Titanium and trying to implement the CommonJS approach. I like the modular setup, but I am wondering how best to deal with things like a shopping cart: temporary, user-created data that needs to last through the lifetime of the app.

I can see three approaches: 1. Create a special module for such a Cart. It will be created the first time it's require()d, and you can access the cart in its current state from any other module by require()ing it from those modules.

  1. Pass a quasi global Cart object to every module that needs it. This is in breach of the letter and the spirit of CommonJS.

  2. Store the Cart in local memory using Ti.App.Properties. This way, the cart is retained even when the user quits the app.

Any thoughts on what would be best?


Solution

  • The solution I'd prefer is to create a CommonJS module the following way:

    function ShoppingCart(options) {
        // do some setup for the shopping cart
    }
    
    ShoppingCart.prototype.add(product, qty)
        // add product to cart
    }
    
    ShoppingCart.prototype.remove(product, qty)
        // remove product from cart
    }
    
    ShoppingCart.prototype.clear()
        // empty cart (and create new, empty one)
    }
    
    // etc.
    
    ShoppingCart = new ShoppingCart();
    
    module.exports = ShoppingCart;
    

    How to access?

    var Cart = require('path/to/ShoppingCart');
    Cart.add();
    Cart.remove();
    Cart.clear();
    

    This creates a kind of singleton which is created the first time you're calling it and it is kept until the app is finished (removed from memory) or you implement the clear method and clean it by yourself. You can also persist the data using this singleton, it's up to you which parts you gonna implement. It's similar to your first idea.

    Your second idea has several disadvantages because data access isn't encapsulated into a module and data is persisted always so you need to detect if it is old and can be removed or not.

    Finally it depends on your task. Do you need persisten storage you should combine the module with a database. Do you need this information only during runtime, the module is enough.