Skip to content

Instantly share code, notes, and snippets.

@headwinds
Last active January 2, 2016 10:29
Show Gist options
  • Save headwinds/8290098 to your computer and use it in GitHub Desktop.
Save headwinds/8290098 to your computer and use it in GitHub Desktop.
EventEmitter inheritance - how you can a pass the handle to a module within an Expressjs request and hang onto to its scope so that it will listen and respond to events
/*
this file has been simplified to show only the event pattern
*/
'use strict';
var util = require("util");
var events = require("events");
var _ = require("underscore");
var UsersController = require('../app/controllers/users/UsersController');
var RoutesController = function(app, passport, auth) {
events.EventEmitter.call(this);
var self = this;
var users = new UsersController();
app.get('/signin', function(req, res){
// you can tack on the users instance to the request.sessions
// thanks to http://stackoverflow.com/questions/15294941/express-js-app-locals-vs-req-locals-vs-req-session
// who explains the differences
req.session.users = users;
users.signin(req, res);
});
// now when users.signin emits its event, it will be caught here
users.on("event_UserController_signIn", function(data) {
console.log("routes - event_test - " + data );
// you can pass the data up to its parent
self.emit("event_RouterController_signIn", data);
});
};
util.inherits(AuthenticationController, events.EventEmitter);
module.exports = RoutesController;
/*
goal:
I've been working with the MEAN github sample by Linnovate and I wanted to add events to each module. This gist shows how I added a events to the UserController and routes modules so that the routes could listen to events from UserController.
For the purpose of this gist, I'm only going show one function which I believe is enough to demonstrate the pattern.
credit:
https://github.com/linnovate/mean
http://stackoverflow.com/questions/15294941/express-js-app-locals-vs-req-locals-vs-req-session
https://gist.github.com/xjamundx/913506
*/
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose');
var User = mongoose.model('User');
var util = require("util");
var events = require("events");
function UsersController() {
events.EventEmitter.call(this);
}
util.inherits(UsersController, events.EventEmitter);
UsersController.prototype.signin = function(req, res) {
console.log(req.session, "UsersController - signin");
// you can store "users", an instance of UserController, on req.session - see routes.js
var data = { test : "hey I heard you want to sign in"};
req.session.users.emit("event_UserController_signIn", data);
// you can also pass that data object to the view to be rendered for what ever reason...
res.render('users/signin', {
title: 'Signin',
message: req.flash('error'),
users: data
});
};
module.exports = UsersController;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment