Skip to content

Instantly share code, notes, and snippets.

@burdiuz
Last active December 5, 2016 19:24
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 burdiuz/b4204ced61822b154424870460fef6ca to your computer and use it in GitHub Desktop.
Save burdiuz/b4204ced61822b154424870460fef6ca to your computer and use it in GitHub Desktop.
MuntiHandler is a callable object that manages handlers for single event
const handlerFactory = (() => {
class Handler {
constructor() {
this._handlers = [];
}
call(target, args) {
for (let [, value] of this._handlers) {
value.apply(target, args);
}
}
add(sub) {
if (sub instanceof Function && this._handlers.indexOf(sub) < 0) {
this._handlers.push(sub);
}
}
remove(sub) {
const index = this._handlers.indexOf(sub);
if (index >= 0) {
this._handlers.splice(index, 1);
}
}
removeAll() {
this._handlers.splice(0, this._handlers.length);
}
}
const wrapper = () => {
throw new Error('Wrapper cannot be called');
};
return (sub = null) => {
const handler = new Handler();
if (sub) {
handler.add(sub);
}
return new Proxy(
wrapper, {
apply: (wrapper, thisObj, args) => handler.call(thisObj, args)
});
}
})();
module && (module.exports = handlerFactory);
const handlerFactory = (sub = null) => {
const handlers = [];
const handler = (...args) => {
for (let handler of handlers) {
handler.apply(null, args);
}
};
handler.add = (sub) => {
if (sub !== handler && sub instanceof Function && handlers.indexOf(sub) < 0) {
handlers.push(sub);
}
return handler;
};
handler.remove = (sub) => {
const index = this._handlers.indexOf(sub);
if (index >= 0) {
this._handlers.splice(index, 1);
}
return handler;
};
handler.removeAll = () => {
handlers.splice(0, handlers.length);
return handler;
};
if (sub) {
handler.add(sub);
}
return handler;
};
module && (module.exports = handlerFactory);
{
"name": "MultiHandlerFactory",
"description": "Create multihandler that calls its sub-handlers",
"version": "0.0.1",
"main": "MultiHandlerFactory.js",
"dependencies": {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment