node.js实现事件发射器和监听器

来源:互联网 发布:公交车刷卡软件 编辑:程序博客网 时间:2024/05/16 13:57

将自定义事件添加到JavaScript对象

        Node里面的许多对象都会分发事件:一个net.Server对象会在每次有新连接时分发一个事件, 一个fs.readStream对象会在文件被打开的时候发出一个事件。 所有这些产生事件的对象都是 events.EventEmitter 的实例。 你可以通过require("events");来访问该模块。

        实现一个简单的发射器:

  1. var events = require("events");
  2. var emitter = events.EventEmitter();
  3. emitter.emit("customEvent");

        可以直接把事件添加到JavaScript对象,需要在对象实例中调用events.EventEmitter.call(this)来在对象中继承EventEmitter功能,还需要把events.EventEmitter.prototype添加到对象的原型中。

  1. Function newObj(){
  2.     Events.EventEmitter.call(this);
  3. }
  4. newObj.prototype.__proto__ = events.EventEmitter.prototype;

        可以直接从对象实例发出事件了。

  1. var obj = new newObj();
  2. obj.emit("someEvent");

实现事件监听器和发射器事件

  1. var events = require("events");
  2. function Account() {
  3.     this.balance = 0;
  4.     events.EventEmitter.call(this);
  5.     this.deposit = function (amount) {
  6.         this.balance +=amount;
  7.         this.emit("balanceChanged");
  8.     };
  9.     this.widthdraw = function (amount) {
  10.         this.balance -=amount;
  11.         this.emit("balanceChanged");
  12.     };
  13. }
  14.  
  15. Account.prototype.__proto__ = events.EventEmitter.prototype;
  16.  
  17. function displayBalance() {
  18.     console.log("Account balance: $%d", this.balance);
  19. }
  20.  
  21. function checkOverdraw() {
  22.     if(this.balance<0){
  23.         console.log("Account overdraw!!!");
  24.     }
  25. }
  26.  
  27. function checkGoal(acc, goal) {
  28.     if(acc.balance > goal){
  29.         console.log("Goal Achieved!!!");
  30.     }
  31. }
  32.  
  33. var account = new Account();
  34. account.on("balanceChanged", displayBalance);
  35. account.on("balanceChanged", checkOverdraw);
  36. account.on("balanceChanged", function () {
  37.     checkGoal(this, 1000);
  38. });
  39. account.deposit(220);
  40. account.deposit(320);
  41. account.deposit(600);
  42. account.widthdraw(1200);
0 0
原创粉丝点击