Node.js自定義對象事件監聽與發射

1、Node.js是以事件驅動的,那咱們自定義的一些js對象就須要能監聽事件以及發射事件。在Node.js中事件使用一個EventEmitter對象發出,該對象在events模塊中。它應該是使用觀察者設計模式來實現把事件監聽器添加到對象以及移除,以前寫OC那塊的時候也有些觀察者設計模式,在OC中也常常用到:通知中心、KVO,也很容易理解.html

.addListener(eventName,callback):將回調函數附加到對象的監聽器中。當eventName的事件被觸發時,回調函數被放置在事件隊列中執行。設計模式

.on(eventName,callback):和.addListener同樣。數組

.once(eventName,callback),也是監聽不過只在第一次被觸發。app

.listeners(eventName):返回一個鏈接到eventName事件的監聽器函數數組。函數

.setMaxListeners(n):若是多於n的監聽器加入到EventRmitter對象,就會出發警報.ui

.removeListener(eventName,callback):將callback函數從EventEmitter對象的eventName事件中移除。this

2、上面寫了那麼多也都是EventEmitter對象方法的使用,自定義的對象怎麼能使用它們纔是關鍵!spa

監聽方法都是在EventEmitter對象,要想讓自定義的對象也能使用這些方法,那就須要繼承EventEmitter。prototype

js中實現繼承有好幾種方法:構造函數、原型鏈、call、apply等,能夠百度一下:js繼承。關於原型對象原型鏈這個寫的挺不錯:http://www.cnblogs.com/shuiyi/p/5305435.html設計

只需將Events.EventEmitter.prototype添加到對象原型中.(在EventEmitter中是經過prototype來添加的監聽器方法)

3、使用

var events = require('events');
function Account() {
    this.balance = 0;
    //買的資料書上寫要添加下面的語句,我將下面語句註釋掉也能實現繼承,應該是不須要的吧
    //events.EventEmitter.call(this);
    this.deposit = function(amount){
        this.balance += amount;
        this.emit('balanceChanged');
    };
    this.withdraw = function(amount){
        this.balance -= amount;
        this.emit('balanceChanged');
    };
}
Account.prototype.__proto__ = events.EventEmitter.prototype;
function displayBalance(){
    console.log("Account balance: $%d", this.balance);
}
function checkOverdraw(){
    if (this.balance < 0){
        console.log("Account overdrawn!!!");
    }
}
function checkGoal(acc, goal){
    if (acc.balance > goal){
        console.log("Goal Achieved!!!");
    }
}
var account = new Account();
account.on("balanceChanged", displayBalance);
account.on("balanceChanged", checkOverdraw);
account.on("balanceChanged", function(){
    checkGoal(this, 1000);
});
account.deposit(220);
account.deposit(320);
account.deposit(600);
account.withdraw(1200);

 

Account balance: $220
Account balance: $540
Account balance: $1140
Goal Achieved!!!
Account balance: $-60
Account overdrawn!!!

Process finished with exit code 0
相關文章
相關標籤/搜索