Skip to content

Instantly share code, notes, and snippets.

@joona
Created February 4, 2020 10:25
Show Gist options
  • Save joona/c9d53bd9cae77680da3426aab7450388 to your computer and use it in GitHub Desktop.
Save joona/c9d53bd9cae77680da3426aab7450388 to your computer and use it in GitHub Desktop.
Store factory
/*
* StoreFactory - Creates plain object to be used as store with listen and dispatch helpers
*/
export default function storeFactory(obj) {
const store = {};
// Create DOM element to be used as store specific event channel
const eventChannel = store._eventChannel = document.createElement('div');
eventChannel.setAttribute('data-store', true);
// Dispatch custom events to store event channel.
// - creates a custom event with <details> payload, and dispatches to eventChannel
store.dispatch = (eventName, details) => {
console.log('[StoreFactory] dispatching event', eventName);
const event = document.createEvent('Event');
event.initEvent(eventName, true, true);
event.detail = details || {};
eventChannel.dispatchEvent(event);
};
// Bind listener store event channel, to be used in components
// - event has dispatched payload in event.details, which will be passed to eventHandler as second argument
store.listen = (eventName, eventHandler) => {
eventChannel.addEventListener(eventName, e => {
eventHandler(e, e.detail);
});
};
// Unbind listener, requires reference to callback
store.unlisten = (eventName, eventHandler) => {
eventChannel.removeEventListener(eventName, eventHandler);
};
Object.assign(store, obj);
// Calls initialize -method on initialization, when defined
if(store.initialize && typeof store.initialize === 'function') {
store.initialize.call(store);
store._initialized = true;
}
return store;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment