Skip to content

Instantly share code, notes, and snippets.

@zenparsing
Last active February 22, 2016 02:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zenparsing/a7284de60ad3c284f1c2 to your computer and use it in GitHub Desktop.
Save zenparsing/a7284de60ad3c284f1c2 to your computer and use it in GitHub Desktop.
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