2015-02-06 55 views
2

我想以特定的順序加載一些我的對象,比如先連接數據庫,然後啓動郵件服務,然後開始加載遊戲的東西,最後我想開始網絡服務器,所以一切都加載之前上網。NodeJS eventEmitter.emit:這不是預期的範圍

我做了一個鏈條是這樣的:

db.on('ready', mail.init); 
mail.on('ready', game.init); 
game.on('ready', ws.start); 
db.init(); 

DB模塊看起來是這樣的:

var config = namespace('config'), 
    mongoose = require('mongoose'), 
    events = require('events'), 
    util = require('util'); 


function DataBase() { 
    events.EventEmitter.call(this); 

    this.init = function() { 
    self = this; 

    mongoose.connect('mongodb://'+config.db.host+':'+config.db.port+'/'+config.db.database); 
    mongoose.connection.on('error', console.error.bind(console, '[Database] ERROR:')); 
    mongoose.connection.once('open', function() { 
     console.log('[database] ready') 
     self.emit('ready', {caller: 'database'}); 
    }); 
    } 
} 

util.inherits(DataBase, events.EventEmitter); 

module.exports = exports = new DataBase(); 

的郵件類看起來是這樣的:

var Mail = function() { 
    events.call(this); 

    this.send = function(mailinfo) { 
    var mailData = { 
     from: config.mail.from, 
     to: to, 
     subject: subject, 
     text: templates[template] 
    }; 



    transporter.sendMail(mailData, function(err, info) { 
     if (err) 
     console.log(err); 
     else 
     console.log('Message sent: ' + info.response); 
    }); 
    } 

    this.init = function(data) { 
    console.log(this.constructor); 
    this.emit('ready', {caller: 'mail'}); 
    } 
} 

util.inherits(Mail, events); 

當我啓動腳本,數據庫正確執行,準備就緒,調用郵件的初始化函數,但是當this.emit爲c時,它會到達一個循環alled。

正如你所看到的,我已經試圖找出爲什麼它無休止地圍繞郵件循環。在

console.log(this.constructor); 

說,它的數據庫,所以不是發光的郵件範圍,它仍然emitts在數據庫範圍,因爲這=數據庫。

爲什麼「這個」在郵件「類」數據庫而不是郵件? 我該如何解決我的問題?我是否創建了錯誤的類?

回答

2

當你做db.on('ready', mail.init)你傳遞郵件init函數作爲回調,但沒有它的上下文。您需要指定上下文,例如與.bind

db.on('ready', mail.init.bind(mail)) 
+0

謝謝!解決了這個問題,你的解釋會有很大的幫助。 – Soma 2015-02-06 14:50:36