Last active
August 29, 2015 14:05
-
-
Save donut/f16040209cdc6f5e62c2 to your computer and use it in GitHub Desktop.
A simple hook system in JavaScript.
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
###* | |
* @file | |
* A hook system. | |
* @see https://gist.github.com/donut/f16040209cdc6f5e62c2 | |
### | |
'use strict' | |
hook = | |
_callbacks: [] | |
###* | |
* Registers a callback with the named hook. | |
* | |
* @param {string} name | |
* The name of the hook to register the callback with. | |
* @param {function} callback | |
* The call back to register with the hook. | |
### | |
register: (name, callback) -> | |
@_callbacks[name] ?= [] | |
@_callbacks[name].push callback | |
###* | |
* Invokes all the callbacks registered with the named hook. | |
* | |
* @param {string} name | |
* The name of the hook. | |
* @param {mixed} parameters... | |
* The arguments to pass to each callback. | |
* @return {array} | |
* The values returned from each callback. If a callback returns an array | |
* its values will be appended to the returned array. | |
### | |
invoke: (name, parameters...) -> | |
return [] unless @_callbacks[name]? | |
results = [] | |
for callback in @_callbacks[name] | |
result = callback parameters... | |
continue unless result? | |
if Array.isArray result | |
results = results.concat result | |
else | |
results.push result | |
results | |
module.exports = hook |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nicely documented!