nodejs事件什么时候使用
发布于 8 年前 作者 fangker 5968 次浏览 来自 问答

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); 以上情况,直接调用函数就行了为什么要用事件,感觉代码多了许多。小白一只,希望大神指教。(例举一个事件的应用场景)。

12 回复

事件机制是为了解耦,并且可以一对多,详见EventEmitter vs Callbacks:https://github.com/yjhjstz/deep-into-node/blob/master/chapter7/chapter7-1.md

@yjhjstz 谢谢指导

请格式化代码块。

@yjhjstz 看到您写的章节,非常过瘾,决定跟随 ~

可以在issue里面讨论

@yjhjstz 跟随学习,有问题,issue讨论非常好~ 花花时间在Node上,值得,毕竟这是目前最主要的活动了-= =-

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)

@hyj1991 谢谢指导

@flamingtop 书写习惯不好啊~

这里的继承更偏向于浏览器环境的Javascript, 对象冒充+原型继承是此环境里很成熟的继承方式,对象冒充就是你注释掉的那一行了

@fangker 不客气,哈哈

回到顶部