Skip to content

Instantly share code, notes, and snippets.

@rfprod
Created June 8, 2017 09:45
Show Gist options
  • Save rfprod/c130ee6dff0daee1770c114ea3c752ce to your computer and use it in GitHub Desktop.
Save rfprod/c130ee6dff0daee1770c114ea3c752ce to your computer and use it in GitHub Desktop.
Custom Events
class CustomEvent {
constructor() {
var handlers = [];
var isolatedHandlers = [];
this.subscribe = (...subs) => {
isolatedHandlers = handlers.slice(0);
for (let sub of subs) {
if (typeof sub === 'function') {
isolatedHandlers.push(sub);
}
}
handlers = isolatedHandlers.slice(0);
};
this.unsubscribe = (...subs) => {
isolatedHandlers = handlers.slice(0);
for (let sub of subs) {
if (isolatedHandlers.includes(sub)) {
const lastIndex = isolatedHandlers.lastIndexOf(sub);
isolatedHandlers.splice(lastIndex, 1);
}
handlers = isolatedHandlers.slice(0);
}
};
this.emit = function(...args) {
for (let h of handlers) {
h.call(this, ...args);
}
};
}
}
// TEST
function l(arr) { arr.push('l'); }
function o(arr) { arr.push('o'); }
var e = new CustomEvent(), bucket = [];
e.subscribe(l, o, l);
e.emit(bucket); // bucket is ['l', 'o', 'l']
e.unsubscribe(o, l);
bucket = [];
e.emit(bucket); //bucket is ['l']

Custom Events

Rules

  • an event object has subscribe and unsubscribe methods to add and remove handlers
  • subscribe and unsubscribe are able to take an arbitrary number of arguments and tolerate invalid arguments (not functions, or for unsubscribe, functions which are not subscribed) by skipping them
  • multiple subscription of the same handler is allowed, and in this case unsubscription removes the last subscription of the same handler
  • an event object has an emit method which must invoke all the handlers with the arguments provided
  • emit uses its own invocation context as handers' invocation context
  • the order of handlers invocation matches the order of subscription
  • handler functions can subscribe and unsubscribe handlers, but the changes apply to the next emit call - the handlers for an ongoing emit call are not affected
  • subscribe, unsubscribe and emit are the only public properties of event objects (apart from Object.prototype methods)

A script by V.

License.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment