Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple custom event hub for simple DOM apps
let CustomEvent = window.CustomEvent;
if (typeof CustomEvent !== "function") {
// Internet Explorer
CustomEvent = function(name, options = {}) {
let {
bubbles = false,
cancelable = false,
detail
} = options;
let evt = document.createEvent("CustomEvent");
evt.initCustomEvent(name, bubbles, cancelable, detail);
return evt;
};
}
class CustomEventHub {
constructor(target) {
if (typeof target === "string") {
let selector = target;
target = window.document.querySelector(selector);
if (!target)
throw new Error(`No element matching selector "${ selector }" found`);
} else if (!target) {
target = window.document.createElement("div");
} else {
target = Object(target);
}
this._target = target;
}
get target() { return this._target; }
listen(event, fn) {
if (typeof fn !== "function")
throw new TypeError(fn + " is not a function");
this._target.addEventListener(event, fn, false);
return _=> { this._target.removeEventListener(event, fn, false) };
}
dispatch(event, options = {}) {
return Promise.resolve().then(_=> {
if (typeof event === "string")
event = new CustomEvent(event, options);
this._target.dispatchEvent(event);
return event;
});
}
static get CustomEvent() { return CustomEvent }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.