Building reactive datastore’s using delegated events in JavaScript

Every time I update my blog I end up coming back to this draft that I’ve never quite managed to polish up into something sensible before. It relates to an interesting pattern I was playing about with – terrifyingly now 5 or so years ago – that I still think is quite cool – even if the wider JS ecosystem has likely now moved past it.

Rather than leaving it sitting in my drafts forever, I thought I’d have a crack at tidying it up and sharing, as I do think there are still a couple of interesting properties, even if these do come with trade-offs.

What I was trying to do

At the time, I was tinkering with my own little Backbone-inspired library called lump.js. I’ve always liked Backbone’s delegated event pattern – being able to manage listeners centrally without constantly binding and unbinding them – and I wanted to see if I could combine that with a more modern reactive datastore using JavaScript Proxies.

The key aims being

  • Make it difficult to accidentally orphan references
  • Interact with the store as if it’s just a normal JavaScript object.
  • Use listeners to react to changes anywhere in the data structure (including for data that doesn’t exist yet).

Broadly I think the solution I came up with does a decent enough job at managing all these goals – even if it does have a few pitfalls I’ll mention later.

Basic usage is – you make a “model” with whatever data you want in it. Then, you can use it just like a normal JS object – changing values, or even entire portions while the events fire so you can listen for these changes.

const data = Model({
    players: [{ id: 1, name: 'Steve', location: [23, 15] }]
});

// Listen for new players being added
data.on('create:players.*', (player) => {
    // Listen for changes on the sub-model itself
    player.on('update:name', (name) => console.log(`My name is now ${name}`));
    player.on('update:location[0]', (x) => console.log(`My x coord is now ${x}`));
    player.on('update:location.1', (y) => console.log(`My y coord is now ${y}`));
    player.on('update:location', (coords) => console.log('My location got updated'));
});

data.players.push({ id: 2, name: 'Ralph' });

Due to the way it works, there’s no risk of orphaning an object (e.g. the player) even if you go and replace big chunks of the object.

const test = Model({
    name: 'bob',
    abilities: {
        jump: { stats: 1 },
        duck: { stats: 2 }
    }
});

let jump = test.abilities.jump;

// Completely replace the parent object
test.abilities = {
    jump: { stats: 5 },
    duck: { stats: 2 },
    other: { stats: 3 }
};

console.log(jump.stats); // now = 5

test.abilities.jump.stats = 10;
console.log(jump.stats); // now = 10

jump.stats = 11;
console.log(test.abilities.jump.stats); // and it's now 11

Normally with something like this, you’d expect replacing test.abilities like that would leave jump pointing at the old object in memory, detached from the store, and any listeners on it would quietly stop firing. Something this setup avoids, letting jump stay in sync and all it’s listeners carry on working as normal. If that data gets deleted entirely, reading from jump just gives you undefined back instead of stale data. It then starts working again as soon as it’s recreated.

That’s all very well but how does it work?

The approach works by setting up two separate Proxy objects: a Data Proxy (to hold information) and an Access Proxy (to read it). The Data Proxy wraps the actual data in the store. It’s job is to intercept changes and compare the affected path against an internal copy of the previous state, then fire the right create, update, or remove events.

Whenever you read an object out of the store, however, you don’t get the Data Proxy directly. Instead, it gets wrapped in the second proxy – the Access Proxy. The Access Proxy is more or less a wrapper around a data path (for example, abilities.jump). Any reads, writes, or .on() calls you make against it are simply routed back to the real store at that path.

Because of this, if your code holds onto let jump = test.abilities.jump, it isn’t really holding a reference to that specific object, instead it’s holding an Access Proxy pointing at abilities.jump. Even if the entire abilities object gets swapped out , jump.stats still resolves against the store at abilities.jump.stats under the hood, so nothing goes out of sync.

To properly put this all through it’s paces, I dogfooded the library heavily against another little experiment at the time RPGQuickEncounter – a stand alone browser based tool for running encounters for tabletop RPG’s like D&D over slack & zoom (Something necessitated by the Covid lockdowns at the time.)

The game effectively lets near instantly setup an encounter on an arbitrary map image, create and manage characters, fog of war, custom icons and all that fun – which all persists nicely into local storage.

This provided a nice way to see how the pattern felt to use in practice – the sorts of things it allowed you to stop worrying about, as well as the things it added you now need to. If you want to have a poke around the code (and the test suite alongside it), the full source for the model is up on GitHub in lump.js/src/model.js. Overall I actually think it worked pretty well – given the code is all hand rolled and libraryless – having components subscribe to paths in the model – without needing to worry about whether a character was edited one field at a time or overwritten wholesale from saved state – kept things clean and easy to reason about – even as the complexity started to grow.

Even some of the quirks with arrays (e.g. if an access proxy ref referenced player[0], and the array got shifted to add a new one in that position – all the refs would now be pointed to that) were actually pretty easy to work with – for example as players were all rendered based on their property, swapping index’s didn’t actually make any odds as positions/data were all preserved.

Great, should we all swap over?

Err, no. While pretty cool (in my opinion), the world has moved on a tad in the past 5 years. Lump was only ever experimental code and never really designed for proper production use and libraries like Vue/Solid have all adopted Proxies in their own way to fit their usage patterns. There’s now even a proper pattern name for parts of this approach – Proxy-backed Cursor – which can be seen in libraries like Legend-state.

If someone ever did want to push this further, there are a few rough edges that need some focus

  • Arrays/shifting indexes – While this actually caused me less issues that I expected once I was used to it, its not an intuitive behaviour and I’m sure could cause all sorts of fun issues if used in production. Figuring out a nice balance between immutable path references, and tracking array index’s in an intuitive way is probably the biggest challenge with this sort of approach.
  • Method collisions – As get, set, on, off are intercepted, these can’t be used a normal attributes. This is probably fixable, but something that’d need a bit of thought
  • Overheads – The diff approach to detecting changes requires the full tree be held twice – not an issue for a small library, but in a bigger complex system this could become a bottleneck.

Whatever the case, while I don’t think any revolution in how people use proxies and manage objects in JS is afoot, it was a fun approach to experiment with and provided a decent developer UX in use. The concept of separating accessing data from storing data is fairly neat trick – and honestly for a tiny self built app – I’d be quite tempted to use it again, even with all its quirks. Who knows, coming back to it fresh I may even solve a few of them.