Skip to content

Instantly share code, notes, and snippets.

@damusix
Last active December 6, 2018 14:27
Show Gist options
  • Save damusix/1da99e76895f7d490efec30432adae32 to your computer and use it in GitHub Desktop.
Save damusix/1da99e76895f7d490efec30432adae32 to your computer and use it in GitHub Desktop.
RiotJS Global Store
// Originally, I was using Redux to contain the state, but switched to RiotControl
// because of its simplicity, and how it makes use of Riot's observable API.
// An issue I found with RiotControl was that, when you register multiple
// stores, it will call 1 event 1 time per store. So if you have 6 stores,
// `RiotControl.trigger('my-event')` will run 6 times. This is incredibly
// inefficient, especially if your app is doing a lot at once.
// After careful consideration, I failed to see the benefit of using
// RiotControl and instead opted for using the native Riot observable API.
// This Gist was born from using RiotControl, research, trial and error.
import MyStore from './my-store';
import MyOtherStore from './my-other-store';
// Declare the global store object
global.app = {}
// Attach observer pattern to global store
riot.observable(global.app);
[MyStore, AnotherStore].forEach(store => new Store(global.app));
export default function AnotherStore(app) {
const self = this;
function changeThingsSomeMore(things) {
things.forEach(thing => thing.changed = true);
}
app.on('thing-changed', changeThingsSomeMore);
}
export default function MyStore(app) {
const self = this;
const things = [];
app.on('my-event', function(thing) {
things.push(thing);
app.trigger('things-changed', things);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment