magic-hook
Extends functions with pre hooks.
Installation
npm i -S magic-hook
Usage
You can add pre hooks
to extend your methods.
'use strict'var hook = // The target function { return a + b} // The hooked functionvar hookedConcat = // A pre hookvar msgNo = 0 { return }hookedConcat for var i = 3; i--; console//> concatenation #1: Hello world!//> concatenation #2: Hello world!//> concatenation #3: Hello world!
Hooks can be removed using removePre
:
hookedConcat console//> Hello world!
To remove all pres associated with a hook just call removePre with no arguments:
hookedConcat
To abort the target function's execution just
don't call the next
function in the pre hook:
hookedConcat console//> The original function was overwritten
You can overwrite the target function's result as well:
var hookedSum = hookedSum console//> 4 console//> 3
Motivation
Suppose you have an object with a save
method.
It would be nice to be able to declare code that runs before save
.
For example, you might want to run validation code before every save
.
Or you might want to create plugins that will modify the input parameters of
your save
method.