dstore: how to create an observable data store

October 15, 2015

Last update: March 28, 2020

Tested with: dstore 1.1.0 with Dojo 1.10.4

dstore is a framework to manage client-side data created by Sitepen (the company behind Dojo Toolkit) and that will be the object store interface for Dojo 2.

The problem

We want to be notified when an action (add, delete or update) is performed on our data store.

A solution

Below a small recipe to create a trackable store: it notifies observers when an action is performed.

require([ "dojo/_base/declare", "dstore/Memory", "dstore/Trackable" ], function(declare, Memory, Trackable) { var Store = declare([Memory, Trackable]); var data = [ { "id": 1, "name": "Test 1" }, { "id": 2, "name": "Test 2" } ]; var store = new Store({"data": data}); var tracker = store.track(); tracker.on("add, update, delete", function(event) { var newIndex = event.index; var oldIndex = event.previousIndex; var object = event.target; // do something more ... }); });

References

  1. Observer pattern on Wikipedia

  2. track() on dstore official documentation


A photo of Elia Contini
Written by
Elia Contini
Sardinian UX engineer and a Front-end web architect based in Switzerland. Marathoner, traveller, wannabe nature photographer.