event是nodejs很重要的部分,但是网上给出的案例感觉没什么实用价值。我一直搞不太懂。比如下面的例子 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); 以上情况,直接调用函数就行了为什么要用事件,感觉代码多了许多。小白一只,希望大神指教。(例举一个事件的应用场景)。
事件机制是为了解耦,并且可以一对多,详见EventEmitter vs Callbacks:https://github.com/yjhjstz/deep-into-node/blob/master/chapter7/chapter7-1.md
Account.prototype.proto(应该是prototype吧) = events.EventEmitter.prototype; 这句话是继承的核心之一,主要作用是把events.EventEmitter的原型方法全部添加到Account类的原型方法里面 至于你注释掉的那句话作用,是因为仅仅上面那行代码,仅仅继承了原型方法,假如在events.EventEmitter构造函数里有this初始化赋值的方法或者属性,Account就没办法继承了,所以完整的继承方式就是 1.Account.prototype.prototype = events.EventEmitter.prototype; 2.在Account的构造函数里面events.EventEmitter.call(this)