Middleware like hooks for node.js


Middleware like hooks for node.js which is useful for building some relations between entities (ODM, ORM, etc).

npm install mhook

Define your actions, bind hooks on them, trigger actions. When you trigger an action all binded hooks will be sequentially executed.

var Hook = require('mhook').Hook;
var hook = new Hook(['beforeUpdate', 'afterUpdate', 'afterRemove']);
// add some hook 
hook.on('beforeUpdate', function(done) {
    // do something, and then say that you done, 
    // pass error as first argument to done 
// add another hook 
hook.on('beforeUpdate', function(done) {
// trigger `action` - executes all two hooks 
hook.trigger('beforeUpdate', [], function(err) {
    // this function will be called after all 
    // hooks done or one of them fail 

for getting on and trigger methods to your object you can inherits from Hook

var Hook = require('mhook').Hook,
    inherits = require('util').inherits;
function Model() {
    // apply parent cunstructor, ['beforeUpdate', 'afterUpdate', 'afterRemove']);
// inherits from Hook 
inherits(Model, Hook);
// now we can use `on` and `trigger` as own methods 
Model.prototype.update = function(objcallback) {
    this.trigger('beforeUpdate', [obj], function(err) {
        if (err) {callback(err); return}
        // update 
        // trigger afterUpdate, etc 
var model = new Model();
model.on('beforeUpdate', function(objdone) {
    console.log('before update object: ', obj);

Hook constructor

accepts array of string actions - possible actions which could be used at on and trigger

Bind hook on action

Trigger some action with hookArgs (arguments which will be passed to every hook function). If callback (accepts error as first argument) function presents it will be called after hooks execution.

into cloned repository run