Package Exports
- magic-hook
- magic-hook/es5
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (magic-hook) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
magic-hook
Extends functions with pre hooks.
Installation
npm install --save magic-hookUsage
You can add pre hooks to extend your methods.
const hook = require('magic-hook')
// The target function
function log(msg) { console.log(msg) }
// The hooked function
const hookedLog = hook(log)
// A pre hook
let msgNo = 0
function counterHook(log, msg) {
log('message #' + (++msgNo) + ': ' + msg)
}
hookedLog.pre(counterHook)
for (let i = 3; i--;) hookedLog('Hello world!')
//> message #1: Hello world!
//> message #2: Hello world!
//> message #3: Hello world!Hooks can be removed using removePre:
hookedLog.removePre(counterHook)
hookedLog('Hello world!')
//> Hello world!
// To remove all the pre hooks associated with a hook just call removePre with no arguments:
hookedLog.removePre()To abort the target function's execution just don't call the next function in the pre hook:
hookedLog.pre(log => console.log('The original function was overwritten'))
hookedLog("Doesn't matter what goes here")
//> The original function was overwrittenYou can overwrite the target function's result as well:
const hookedSum = hook((a, b) => a + b)
hookedSum.pre(function(sum, a, b) {
if (a === 1 && b === 1) return 3
return sum(a, b)
})
hookedSum(2, 2)
//> 4
hookedSum(1, 1)
//> 3Motivation
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.
License
MIT © Zoltan Kochan