使用Express框架的Node.js中的自定义事件 [英] Custom Events in Node.js with Express framework
问题描述
因此,我想知道如何在node.js中创建自定义事件,而我正在碰壁.我很确定我误解了Express的工作原理和node.js事件的工作原理.
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 这就是应用程序.
当用户创建新的活动"(将会发生多次)时,他们会发送POST请求.然后在我的路由中,如果该POST成功,我想发出一个事件,该事件告诉socket.io为该活动创建一个新的命名空间.
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.
在我的路线文件中:
var eventEmitter = require('events').EventEmitter;
// Tell socket.io about the new space.
eventEmitter.emit('new activity', {activityId: body.id});
和socket.io:
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
});
});
所以我得到的错误是无法调用未定义的方法,它指的是上面socket.io中的第2行.我想我正在弄乱我的要求,也许...或者我不太了解事件的工作原理.
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.
任何帮助,甚至包括对Node.js事件的良好阅读的参考,都会动摇!
Any help, even a reference to good reading on Node.js events would rock!
谢谢!
推荐答案
您应该将EventEmitter视为可以继承的类.试试这个:
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!");
这篇关于使用Express框架的Node.js中的自定义事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!