Last active
December 5, 2016 19:24
-
-
Save burdiuz/b4204ced61822b154424870460fef6ca to your computer and use it in GitHub Desktop.
MuntiHandler is a callable object that manages handlers for single event
This file contains 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
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); |
This file contains 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
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); |
This file contains 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
{ | |
"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