Skip to content

Instantly share code, notes, and snippets.

@donut donut/CaptainHook.coffee
Last active Aug 29, 2015

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Oct 18, 2014

nicely documented!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.