发出事件不会触发

Emit event doesn't fire

我的发射事件只是不想触发。我是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;

app.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
});

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

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;

您的 this 关键字失去了 "newClient" 对象的范围,您应该做类似的东西。

var self = this;

然后,在监听器内部调用

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

为了让它发挥作用。

看看这个linkClass loses "this" scope when calling prototype functions by reference