nodejs 之 事件

EventEmitter类的使用

const EventEmitter=require('events').EventEmitter;//导入EventEmitter类
const log = console.log;
const e = new EventEmitter();
e.on('hello',()=>{
  log('hello world');
});//监听hello事件
e.on('bye',()=>{
  log('goodbye');
  process.exit();
})//监听bye事件
setInterval(()=>{
    e.emit('hello')//触发hello事件
},1000);
setTimeout(()=>{
    e.emit('bye')//触发bye事件
},5000)

使用原型继承EventEmitter类

首先理解nodejs中this的指向问题:
1.全局下的this指向module.exports;
2.普通函数中的this指向global对象,
3.构造函数中this指向实例化对象
举个实例来说明原型继承:
dog.js:

const EventEmitter = require('events').EventEmitter;

function Dog(name,energy){
    var _name = name;
    var _energy = energy;
    var that = this;
    EventEmitter.call(this);

    var timer = setInterval(()=>{
        if(energy > 0){
            that.emit('bark');
            _enerrgy--;
}
        if(_energy < 0){
            clearInterval(timer);
}
},1000);
  this.name = ()=> _name;
  this.energy = () => _energy; 
}
Dog.prototype = EventEmitter.prototype;
module.exports = Dog;

play-dog.js

const Dog = require('./dog.js');
var tadi = new Dog('tadi',4);
var zangao = new Dog('zangao',8);
tadi.on('bark',onBark);
zangao.on('bark',onBark);
function onBark(){
  console.log('%s barked! energy: %s', this.name(), this.energy())
}

util.inherts方法继承EventEmitter类

util.inherits(constructor, superConstructor)
此方法有2个参数: 此方法参数针对的都是构造函数
constructor : 构造函数
superConstructor: 父类构造函数
radio.js

#/usr/bin/node
const EventEmitter = require('events').EventEmitter;
const util = require('util');
function Radio(station){
  EventEmitter.call(this);
  var self = this;
  setTimeout(()=>{
    self.emit('open',station);
},0);
  setTimeout(()=>{
    self.emit('stop',station);    
},5000);  
}
util.inherits(Radio,EventEmitter);
modules.exports = Radio;

listen-radio.js

const Radio = require('./radio.js') ;
const station = {
  freq:'106.7';
  name:'music radio'
};
var radio = new Radio(station);
radio.on('open', (station) => {
  console.log('"%s" FM %s opened', station.name, station.freq);
  console.log('lalala...');
});

radio.on('stop', (station) => {
  console.log('"%s" FM %s closed', station.name, station.freq);
});

复制EventEmitter类成员

const EventEmitter = require('events').EventEmitter;

function Radion(station){
  var that = this;
  for(var m in EventEmitter.prototype){
  this[m] = EventEmitter.prototype[m];
}
  setTimeout(()=>{
  that.emit('play',station);
},0);
  setTimeout(()=>{
  that.emit('stop',station);
},5000);
}
module.exports = Radio;
#!/usr/bin/node

const Radio   = require('./04-radio.js'),
      station = {
        'freq': '106.7',
        'name': 'music Radio'
      };

var r = new Radio(station);

r.on('play', (station) => {
  console.log('FM %s %s is playing!', station.freq, station.name);
});

r.on('stop', (station) => {
  console.log('FM %s %s is stop!', station.freq, station.name);
});

自己实现事件机制

#!/usr/bin/node

function Dog(name, energy) {
  var _listeners = {};

  this.name = name;
  this.energy = energy;

  var timer = setInterval(() => {
    if(energy > 0) {
      emit('bark');
      this.energy--;
    }

    if(this.energy < 0) {
      clearInterval(timer);
    }
  }, 1000);

  this.on = (evt, fn) => {
    if(typeof(_listeners[evt]) === 'undefined') {
      _listeners[evt] = [];
    }

    _listeners[evt].push(fn);
  };

  function emit(evt, arg) {
    if(typeof(_listeners[evt]) === 'undefined') {
      console.error('Error: %s not defined!', evt);
      process.exit(1);
    }

    _listeners[evt].forEach((fn) => {
      fn.call(this, arg);
    });
  }
}

module.exports = Dog;
#!/usr/bin/node

const Dog = require('./05-dog.js');

var taidi  = new Dog('taidi', 4),
    zangao = new Dog('zangao', 8);

taidi.on('bark', onBark.bind(taidi));
zangao.on('bark', onBark.bind(zangao));

function onBark() {
  console.log('%s barked! energy: %s', this.name, this.energy);
}

你可能感兴趣的:(nodejs 之 事件)