当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Node.js emitter.eventNames()用法及代码示例


在Node.js中,大多数核心API都是围绕惯用的异步和event-driven体系结构构建的。 EventEmitter类具有所有对象作为事件发出的实例,这些对象在这些实例中公开eventEmitter.on()函数。为了处理事件,有必要导入事件库(require(‘events’))。

itter.eventNames()(在v6.0.0中添加)方法是事件模块的内置应用程序编程接口,用于列出发射器已为其注册侦听器并以数组形式返回的事件。这些侦听器的类型是字符串或符号。

用法:

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

参数:该函数不接受任何参数。

返回值<Array>:它返回一个包含字符串或Symbol值的数组,列出发射器已为其注册侦听器的事件。



范例1: 文件名:index.js

// Node.js program to demonstrate the  
// emitter.eventNames() method  
  
// Using require to access events module  
const EventEmitter = require('events'); 
  
// Creating new event Emitter 
const newEventEmitter = new EventEmitter(); 
  
// Creating new event akash 
newEventEmitter.on('akash', () => {}); 
  
// Creating new event hadii 
newEventEmitter.on('hadii', function() {}); 
  
// Error monitor function 
console.log(EventEmitter.errorMonitor); 
  
// Creating new symbol event newSymbol 
const newSym = Symbol('newSymbolofGeekyWorld'); 
newEventEmitter.on(newSym, () => {}); 
  
// Printing event Names 
console.log(newEventEmitter.eventNames()); 
// Prints:[ 'akash', 'hadii',  
// Symbol(newSymbolofGeekyWorld) ]

输出:

Symbol(events.errorMonitor)

[ ‘akash’, ‘hadii’, Symbol(newSymbolofGeekyWorld) ]

范例2: 文件名:index.js

// Node.js program to demonstrate the  
// emitter.eventNames() method  
  
// Using require to access events module  
const EventEmitter = require('events'); 
  
// Creating new event Emitter 
const newEventEmitter = new EventEmitter(); 
  
// Creating a new callback function  
const someCallback = () => { 
  console.log('Connected to something!'); 
}; 
  
// Creating new event connectSomething 
newEventEmitter.on('connectSomething', someCallback); 
  
// Creating new event alfa 
newEventEmitter.prependListener('alfa', () => console.log('b')); 
  
// Creating new event alfa, not added to eventnames array... 
newEventEmitter.once('geeksforgeeks',  
() => console.log('print in console...')); 
  
// Creating new event alfa, not added to eventnames array... 
newEventEmitter.prependOnceListener('geeksforgeeks',  
() => console.log('geeksforgeeks')); 
  
// Emitting geeksforgeeks event 
newEventEmitter.emit('geeksforgeeks'); 
  
// Creating new symbol event newSymbolofGeekyWorld 
const newSym = Symbol('newSymbolofGeekyWorld'); 
newEventEmitter.on(newSym, () => {}); 
  
// Printing event Names 
console.log(newEventEmitter.eventNames()); 
  
// Removing connectSomething event 
newEventEmitter.removeListener('connectSomething', someCallback); 
  
// Printing event Names 
console.log(newEventEmitter.eventNames());

使用以下命令运行index.js文件:

node index.js

输出:

geeksforgeeks

print in console…

[ ‘connectSomething’, ‘alfa’, Symbol(newSymbolofGeekyWorld) ]

[ ‘alfa’, Symbol(newSymbolofGeekyWorld) ]

参考:https://nodejs.org/api/events.html#events_emitter_eventnames




相关用法


注:本文由纯净天空筛选整理自vikas_g大神的英文原创作品 Node.js emitter.eventNames() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。