simple-event-dispatch
v1.2.1
Published
A simple event dispatcher for loosely coupling code
Downloads
1
Readme
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
});
});
});