15

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!!!

1
  • 1
    Just a heads up, I've since pulled this app down. Commented Oct 10, 2014 at 20:58

2 Answers 2

24

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)
Sign up to request clarification or add additional context in comments.

Comments

11

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!");

1 Comment

If you don't need to add functionality, var EventEmitter = require('events').EventEmitter; var myEmitter = new EventEmitter; works as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.