Created
April 24, 2017 20:50
-
-
Save joona/2128881568e2b5ed5e495a2b6a9c1ac2 to your computer and use it in GitHub Desktop.
CustomEvent based dispatch, listen and action dispatch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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