Skip to content

Instantly share code, notes, and snippets.

@joona
Created April 24, 2017 20:50
Show Gist options
  • Save joona/2128881568e2b5ed5e495a2b6a9c1ac2 to your computer and use it in GitHub Desktop.
Save joona/2128881568e2b5ed5e495a2b6a9c1ac2 to your computer and use it in GitHub Desktop.
CustomEvent based dispatch, listen and action dispatch
export function dispatch(el, eventName, payload, options) {
options || (options = {});
el || (el = document);
el = el.el || el;
var event = new CustomEvent(eventName, {
detail: payload || {},
bubbles: options.bubbles !== false
});
el.dispatchEvent(event);
}
export function listen(el, eventName, callback) {
el || (el = document);
el = el.el || el;
el.addEventListener(eventName, callback);
return callback; // return callback reference for unbinding
}
export function dispatchAction(actionName, payload, el) {
el || (el = document);
const action = {
action: actionName,
payload: payload || {}
};
dispatch(el, 'action', action);
}
export function dispatcher(handler) {
listen(document, 'action', e => {
var action = e.detail.action;
var payload = e.detail.payload || {};
handler.call(this, action, Object.assign({}, payload));
e.stopPropagation();
return false;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment