2015-10-17 132 views
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; 

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 
}); 
+0

從哪裏來的「客戶端」模塊?在var Client = require('client'); –

+0

該模塊有效。我的意思是他的事件(loggedOn,loggedOff,錯誤)的作品。所以現在我想進一步傳送它們。 – SLI

+1

很難測試你在做什麼,因爲我不是很明白什麼是,但是我可以在這裏看到兩件事情,當你使用「var newClient = new Client(嘗試在構造函數中使用相同名稱的newClient );」並且可能你在事件監聽器函數內部放棄了這個範圍。可能這可以幫助http://stackoverflow.com/questions/19457294/class-loses-this-scope-when-calling-prototype-functions-by-reference –

回答

2

關鍵字輸「newClient」對象的範圍,你應該做的東西等。

var self = this; 

然後,聽衆裏面調用作爲

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

爲了使它的工作原理。

看看這個鏈接Class loses "this" scope when calling prototype functions by reference

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; 
+0

不錯,很好的工作。 –