1

我的发射事件只是不想触发。我是 nodejs 的新手,很抱歉犯了愚蠢的错误,但我无法解决几个小时。

客户端模块

var Client = require('steam');
var EventEmitter = require('events').EventEmitter;

var newClient = function(user, pass){
    EventEmitter.call(this);

    this.userName = user;
    this.password = pass;

    var newClient = new Client();
    newClient.on('loggedOn', function() {
        console.log('Logged in.'); // this work
        this.emit('iConnected'); // this don't work
    });

    newClient.on('loggedOff', function() {
        console.log('Disconnected.'); // this work
        this.emit('iDisconnected'); // this don't work
    });

    newClient.on('error', function(e) {
        console.log('Error'); // this work
        this.emit('iError'); // this don't work
    });
}
require('util').inherits(newClient, EventEmitter);

module.exports = newClient;

应用程序.js

var client = new newClient('login', 'pass');

client.on('iConnected', function(){
    console.log('iConnected'); // i can't see this event
});

client.on('iError', function(e){
    console.log('iError'); // i can't see this event
});
4

2 回答 2

2

这是一个范围问题。现在一切正常。

var newClient = function(user, pass){
    EventEmitter.call(this);

    var self = this; // this help's me

    this.userName = user;
    this.password = pass;

    var newClient = new Client();
    newClient.on('loggedOn', function() {
        console.log('Logged in.');
        self.emit('iConnected'); // change this to self
    });

    newClient.on('loggedOff', function() {
        console.log('Disconnected.');
        self.emit('iDisconnected'); // change this to self
    });

    newClient.on('error', function(e) {
        console.log('Error');
        self.emit('iError'); // change this to self
    });
}
require('util').inherits(newClient, EventEmitter);

module.exports = newClient;
于 2015-10-17T01:58:22.763 回答
2

你的this关键字失去了“newClient”对象的范围,你应该做类似的事情。

var self = this;

然后,在侦听器内部调用

newClient.on('loggedOn', function() {
    console.log('Logged in.');
    self.emit('iConnected'); // change this to self
});

为了使它起作用。

看看这个链接类在通过引用调用原型函数时失去“this”范围

于 2015-10-17T02:02:51.493 回答