在node.js中使用emit函数
我不明白为什么我不能让我的服务器运行发射功能。
这是我的代码:
myServer.prototype = new events.EventEmitter;
function myServer(map, port, server) {
...
this.start = function () {
console.log("here");
this.server.listen(port, function () {
console.log(counterLock);
console.log("here-2");
this.emit('start');
this.isStarted = true;
});
}
listener HERE...
}
侦听器是:
this.on('start',function(){
console.log("wtf");
});
所有控制台类型都是这样:
here
here-2
知道为什么它不会打印 'wtf'
吗?
I can't figure out why I can't make my server to run emit function.
Here's my code:
myServer.prototype = new events.EventEmitter;
function myServer(map, port, server) {
...
this.start = function () {
console.log("here");
this.server.listen(port, function () {
console.log(counterLock);
console.log("here-2");
this.emit('start');
this.isStarted = true;
});
}
listener HERE...
}
The listener is:
this.on('start',function(){
console.log("wtf");
});
All the console types is this:
here
here-2
Any idea why it wont print 'wtf'
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,我们缺少一些代码,但我很确定
listen
回调中的this
不会是您的myServer
对象。您应该在回调外部缓存对它的引用,并使用该引用...
...或者将外部
this
值绑定到回调...Well, we're missing some code, but I'm pretty sure
this
in thelisten
callback won't be yourmyServer
object.You should cache a reference to it outside the callback, and use that reference...
...or
bind
the outerthis
value to the callback...对于新手,请确保使用 ES6 arrow function 只要你可以将“this”的上下文绑定到你的函数。
For new people, make sure to you use the ES6 arrow function whenever you can to bind the context of "this" to your function.