Skip to content
Dan Stocker edited this page May 1, 2012 · 6 revisions

Flock is a very simple in-memory key-value store to keep track of data in a NoSQL-y way, providing means to easily and consistently access and manage a tree of data.

Creating the cache

Typical empty cache

var cache;
cache = flock();

Initialized with JSON

cache = flock({
    it: "is the initial",
    state: {
        of: "the",
        data: "store"
    }
});

Direct access to the data object

alert(cache.root); // {...}

You need direct access to feed data retrieved from a flock cache into a business object, DOM element, etc. When accessing data within the datastore, it is safe to use built-in methods of the library.

Adding a node

cache.set('it.is.my.path', 'value');
alert(cache.root.it.is.my.path); // "value"

Nodes on the path that don't exist will be created by .set().

Argument 'value' can be any JavaScript variable. In case 'value' is an object or array, its child values become instantly accessible by their paths. For instance:

cache.set('foo.bar', {hello: "world"});
alert(cache.get('foo.bar.hello').root); // "world"

Retrieving a specific node

Method .get returns a specified datastore node, wrapped in a flock object, making the same methods and thus functionality available on it.

cache.get('it.is.my.path'); // flock("value")

Deleting a node

cache.unset('it.is.my.path');
alert(cache.unset('it.is.my.path').root); // undefined

Retrieving multiple nodes

It is possible to retrieve more than one node with .query().

Take the following data structure:

cache = flock({
    name: "Bob",
    age: 34,
    children: {
        Betty: {
            name: "Betty",
            age: 4
        },
        Benji: {
            name: "Benji",
            age: 12
        }
    }
});

Then we can use wildcards (either "*" or "...") to express queries. The asterisk stands for all nodes on a given level, while the three dots traverse until the adjacent key in the path is found. Traversal doesn't follow loopbacks.

cache.query('children.*.name');    // ["Betty", "Benji"]
cache.query('...name');            // ["Bob", "Betty", "Benji"]

Events

Flock lets you trace changes within data structures, as well as create and capture your own custom events.

The code below illustrates how to subscibe to such changes. It shows an alert every time anything under the node 'children.Betty' changes.

cache.on('children.Betty', 'change', function (event, data) {
    alert("The node " + event.target + "changed from " + data.before + " to " + data.after);
});

// ...

cache.set('children.Betty.age', 5);

Clone this wiki locally