NodeJS3-3基础API----event(事件触发器)

1.基础(on)


// 如果像对象享有事件能力就要集成EventEmitter const EventEmitter = require('events') //集成EventEmitter类 class CustomEvent extends EventEmitter{ } // 实例化对象 const ce = new CustomEvent() //绑定一个事件名 ce.on('test',()=>{ console.log('this is a test'); }) setInterval(()=>{ ce.emit('test') },500)

运行效果就是不断的执行this is a test

2.传一些参数,基础信息

const EventEmitter = require('events')

class CustomEvent extends EventEmitter{}
const ce = new CustomEvent() 

ce.on('error',(err,time)=>{
    console.log(err);
    console.log(time);
    
});

ce.emit('error',new Error('oops!'),Date.now())

3.执行一次就好了 once(下面即使是像之前on那样操作,也就是每个500毫秒执行一次,可是运行之后也就执行一次而已)

const EventEmitter = require('events')
class CustomEvent extends EventEmitter{}

const ce = new CustomEvent()
ce.once('test',()=>{
    console.log('test event');
    
})
setInterval(()=>{
    ce.emit('test')
},500)

4.移除工作,绑定了一些事件在某些场景下需要移除掉(removeListener  或者 removeAllListener)

const EventEmitter = require('events')
class CustomEvent extends EventEmitter{}
function fn1(){
    console.log('fn1');
}
function fn2(){
    console.log('fn2');
}
const ce = new CustomEvent()
ce.on('test',fn1)
ce.on('test',fn2)
setInterval(()=>{
    ce.emit('test')
},500)
setTimeout(()=>{
    // ce.removeListener('test',fn2)
    // ce.removeListener('test',fn1)
    //移除所有事件名的事件
    ce.removeAllListeners('test')
},1500)

 

posted @ 2019-08-27 16:41  KIU的博客  阅读(308)  评论(0编辑  收藏  举报