Package Exports
- magic-hook
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. Inspired by hooks-js.
Installation
$ npm install --save magic-hookMotivation
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.
Why no post hook as well?
post hooks are the same as events, so no need to replicate the functionality of
a regular event emitter.
Usage
We can add pre hooks to extend our methods.
var logger = require('logger');
var magicHook = require('magic-hook');
magicHook(logger, ['log']);
logger.pre('log', function(next, msg) {
next('hooked message: ' + msg);
});
logger.pre('log', function(next, msg) {
console.log(msg);
next(msg);
});
/* will log "hooked message: Hello world!" to the console and log it with logger */
logger.log('Hello world!');You can hook all methods of an object by simply not specifying the list of methods to hook:
var magicHook = require('magic-hook');
magicHook(Math);
Math.pre('max', function(next, a, b) {
console.log('max method called');
next(a, b);
});
/* will log to a message to console and assign the max number to maxNumber */
var maxNumber = Math.max(32, 100);Removing pres
You can remove a particular pre associated with a hook:
logger.pre('log', someFn);
logger.removePre('log', someFn);And you can also remove all pres associated with a hook:
logger.removePre('log'); /* Removes all declared pres on the hook 'log' */License
The MIT License (MIT)