Javascript 在 node.js 中使用发射函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8752886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using emit function in node.js
提问by Itzik984
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'
?
知道为什么它不会打印'wtf'
吗?
回答by
Well, we're missing some code, but I'm pretty sure this
in the listen
callback won't be your myServer
object.
好了,我们缺少一些代码,但我敢肯定,this
在listen
回调不会是你的myServer
对象。
You should cache a reference to it outside the callback, and use that reference...
您应该在回调之外缓存对它的引用,并使用该引用...
function myServer(map, port, server) {
this.start = function () {
console.log("here");
var my_serv = this; // reference your myServer object
this.server.listen(port, function () {
console.log(counterLock);
console.log("here-2");
my_serv.emit('start'); // and use it here
my_serv.isStarted = true;
});
}
this.on('start',function(){
console.log("wtf");
});
}
...or bind
the outer this
value to the callback...
...或回调bind
的外部this
值...
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;
}.bind( this )); // bind your myServer object to "this" in the callback
};
this.on('start',function(){
console.log("wtf");
});
}
回答by Lyks
For new people, make sure to you use the ES6 arrow functionwhenever you can to bind the context of "this" to your function.
对于新用户,请确保在可以将“this”的上下文绑定到您的函数时使用 ES6箭头函数。
// Automatically bind the context
function() {
}
() => {
}
// You can remove () when there is only one arg
function(arg) {
}
arg => {
}
// inline Arrow function doesn't need { }
// and will automatically return
function(nb) {
return nb * 2;
}
(nb) => nb * 2;