Skip to content

Instantly share code, notes, and snippets.

@donut
Last active August 29, 2015 14:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donut/f16040209cdc6f5e62c2 to your computer and use it in GitHub Desktop.
Save donut/f16040209cdc6f5e62c2 to your computer and use it in GitHub Desktop.
A simple hook system in JavaScript.
###*
* @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
@zzz6519003
Copy link

nicely documented!

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