Skip to content

Instantly share code, notes, and snippets.

Last active Aug 29, 2015
What would you like to do?
A simple hook system in JavaScript.
* @file
* A hook system.
* @see
'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
results.push result
module.exports = hook
Copy link

zzz6519003 commented Oct 18, 2014

nicely documented!

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