EventEmitter

Posted on Posted in development

Our EventEmitter in PhantomSQL is based on NodeJS version so they should be compatible. Here are couple examples on how to use the emitter.

Basic usage of registering and listening to an event.

"use strict";
 
const {EventEmitter} = require('events');
 
// Dump all the args
em.on('hello-event', (...arg)=> {console.info("Hello event handler : " + arg)});
// Handler without args
em.on('hello-event', ()=> {console.info("Another handler")});
// passed in arguments
em.on('hello-event', (id, val)=> {console.info("Handler :"+id +", "+ val)});
 
// emit event
em.emit('hello-event', 123, 'ABC');

A more typical example would be to extend via prototype.

"use strict";
const {EventEmitter} = require('events');
 
function HelloService()
{
	// Extends via prototype
	Object.setPrototypeOf(HelloService.prototype, EventEmitter.prototype);
 
	this.hello = function()
	{
		console.info("Hello service called");
		this.emit('hello');
	}
}  
 
const service = new HelloService();
 
service.on('hello', ()=> {console.info("Hello Handler called")});
service.hello();

Leave a Reply

Your email address will not be published. Required fields are marked *