Costa Michailidis
Costa Michailidis

Reputation: 8178

Custom Events in Node.js with Express framework

So, I'd like to know how to create custom events in node.js, and I'm hitting a wall. I'm pretty sure I'm misunderstanding something about how express works and how node.js events work.

https://creativespace.nodejitsu.com That's the app.

When a user creates a new "activity" (something that will happen many times) they send a POST request. Then within my route, if that POST succeeds I'd like to emit an event, that tells socket.io to create a new namespace for that activity.

In my route file:

var eventEmitter = require('events').EventEmitter;    
// Tell socket.io about the new space.
eventEmitter.emit('new activity', {activityId: body.id});

And socket.io:

// When someone creates a new activity
eventEmitter.on('new activity', function (data) {  // this gives and error
  var newActivity = '/activity?' + data.activityId;
  io.of(newActivity).on('connection', function (socket) {

    // Socket.io code for an activity

  });
});

So the error I get is CANNOT CALL METHOD ON OF UNDEFINED and it refers to what would be line 2 in the socket.io above. I think I'm messing up my requires, maybe...or I'm not quite understanding how events work.

Any help, even a reference to good reading on Node.js events would rock!

Thanks!!!

Upvotes: 15

Views: 12729

Answers (2)

Jay
Jay

Reputation: 496

If using express you can also just listen for event on the express 'app' which inherits from EventEmitter. For example:

res.app.on("myEvent", function)

and emit to it like

res.app.emit("myEvent", data)

Upvotes: 24

Todd Yandell
Todd Yandell

Reputation: 14696

You should treat EventEmitter as a class you can inherit from. Try this:

function MyEmitter () {
  events.EventEmitter.call(this);
}

util.inherits(MyEmitter, events.EventEmitter);

Now you can use your class to listen and emit events:

var e = new MyEmitter;
e.on("test", function (m) { console.log(m); });
e.emit("test", "Hello World!");

Upvotes: 11

Related Questions