1.2.1 • Published 8 years ago

simple-event-dispatch v1.2.1

Weekly downloads
4
License
MIT
Repository
github
Last release
8 years ago

Build Status

simple-event-dispatch

A simple event dispatcher for loosely coupling code

Install

npm install simple-event-dispatch --save

Example usage in an Express application

comment-controller.js

var dispatch = require('simple-event-dispatch');

/**
 * Create the comment dispatch module
 */
var commentDispatch = dispatch.module('Comment');

/**
 * Create a comment. The first parameter is always a deferred object
 */
commentDispatch.listen('create', function(deferred, comment) {
  if (!comment) {
    return deferred.reject(new Error('Comment#create expects a comment object'));
  }

  Comment.createAsync({
      author: comment.author,
      body: comment.body,
      parent: comment.parent
    })
    .then(function(comment) {
      // Do some stuff...
      deferred.resolve(comment);
    })
    .catch(function(err) {
      // Do some more stuff...
      deferred.reject(err);
    });
});

Somewhere in app.js

/**
 * Register the comment dispatcher. The comment dispatcher is now available 
 * anywhere through simple-event-dispatch
 */
require('./comment-controller.js');

comment-routes.js

var dispatch = require('simple-event-dispatch');

router.post('/create', function(req, res) {
  /**
   * Trigger the comment dispatcher
   */
  dispatch.trigger('Comment', 'create', req.body.comment)
    .then(function(comment) {
      res.status(200).json({
        resource: comment
      });
    })
    .catch(function(err) {
      res.status(err.status || 500).json({
        message: err.message
      });
    });
});

module.exports = router;

Or:

/**
 * Retrieve the comment dispatcher instance
 */
var commentDispatch = dispatch.module('Comment');

router.post('/create', function(req, res) {
  commentDispatch.trigger('create', req.body.comment)
    .then(function(comment) {
      res.status(200).json({
        resource: comment
      });
    })
    .catch(function(err) {
      res.status(err.status || 500).json({
        message: err.message
      });
    });
});
1.2.1

8 years ago

1.2.0

8 years ago

1.1.2

8 years ago

1.1.0

8 years ago

0.0.3

8 years ago

0.0.2

8 years ago

1.0.0

8 years ago