node 基础API(event)

// 绑定事件
const EventEmitter=require(‘events‘);

class CustomEvent extends EventEmitter{}

const ce=new CustomEvent();

ce.on(‘test‘,()=>{
    console.log(‘this is a test‘);
});

setInterval(()=>{
    ce.emit(‘test‘)
},1000)

 

传参:

const EventEmitter=require(‘events‘);

class CustomEvent extends EventEmitter{}

const ce=new CustomEvent();

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

ce.emit(‘error‘,new Error(‘oops!‘));

// Error: oops!

// 多个参数
ce.on(‘error‘,(err,time)=>{
    console.log(err);
    console.log(time);
});

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

// Error: oops!
// 1563287056187

调用一次:

const EventEmitter=require(‘events‘);

class CustomEvent extends EventEmitter{}

const ce=new CustomEvent();

ce.once(‘test‘,()=>{
    console.log(‘test‘);
});

setInterval(()=>{
    ce.emit(‘test‘);
},500);

// test  一次

移出事件:

const EventEmitter=require(‘events‘);

class CustomEvent extends EventEmitter{}

const ce=new CustomEvent();

function fn1(){
    console.log(‘fn1‘);
}

function fn2(){
    console.log(‘fn2‘);
}

ce.on(‘test‘,fn1);
ce.on(‘test‘,fn2);

setInterval(()=>{
    ce.emit(‘test‘)
},1000);

setTimeout(()=>{
    // ce.removeListener(‘test‘,fn1);  // 移除单个

    ce.removeAllListeners(‘test‘)
},3000)

 

node 基础API(event)

上一篇:WPFの触发器详解


下一篇:c# WinForm MessageBox弹窗倒计时的自动关闭