在node.js中使用emit函数
我不明白为什么我不能让我的服务器运行发射function。
这是我的代码:
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"); });
所有的控制台types是这样的:
here here-2
任何想法,为什么它不会打印'wtf'
?
那么,我们错过了一些代码,但我很确定this
在callback中不会是你的myServer
对象。
您应该在callback之外caching一个引用,并使用该引用…
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"); }); }
…或bind
外部this
值bind
到callback…
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"); }); }