Nodejs事件注册及调用方式

事件注册监听

<!-- lang: js -->
    var EventEmitter = require('events').EventEmitter;
    var event = new EventEmitter();

    event.on('some_event',function(){
        console.log('some_event occured');
    });
    //或者
    event.addListener('some_event',function(){
        console.log('some_event occured');
    });

    //注册一次事件,事件触发后就被自动移除
    event.once('some-once',function(){
        console.log('some-once occured');
    });

事件触发

<!-- lang: js -->
event.emit('some_event');
event.emit('some-once');

移除事件监听

<!-- lang: js -->
//移除所有监听
event.removeAllListeners();

//移除某一事件监听
event.removeListener('事件名称','监听函数名称');

你可能感兴趣的:(JavaScript,nodejs,event)