Search code examples
javascriptnode.jsdom-eventschild-processeventemitter

Create events object after some data was


I've several events which I need to listen to with additional event and pass object:

const spawn = require('child_process').spawn;
const ls = spawn('ls', ['-lh', '/usr']);

ls.stderr.on('data', (data) => {
  myObj.data = true
  //here I need to raise the event with the property data
});

ls.on('close', (code) => {
  myObj.close = true
  //here I need to raise the event with the property close
});

For example inside of every event I want to emit my events and send object with property. For example raise myEvent with my object and every following event will update property in my object like data,close,open

Let's say this is my object

var myObj ={
  open:true,
  data:false,
  close:true
}

How can I do this?


Solution

  • The obvious way is to code your own small event emitter/listener.

    const spawn = require('child_process').spawn;
    const ls = spawn('ls', ['-lh', '/usr']);
    
    var eventer = {
        events: {},
        on: function(event, callback){
           if(!(typeof callback === 'function'){
               return;
           }
           if(!this.events[event]){
               this.events[event] = [];
           }
           this.events[event].push(callback);
       },
       trigger: function(event, data){
           if(!this.events[event]){
               this.events[event] = [];
           }
           this.events[event].forEach(function(callback){
               callback(data);
           }
       }
    }
    var myObj = {
       open: true,
       data: false,
       close: true
    }
    
    ls.on('close', (code) => {
        myObj.close = true;
        eventer.trigger('data-changed', myObj);
    });
    
    ls.stderr.on('data', (data) => {
        myObj.data = true;
        eventer.trigger('data-changed', myObj);
    });
    
    eventer.on('data-changed', (data) => {
         //action on close
    });
    

    Edit

    Since you're on Node, you can use the EventEmitter, which works in a similar way:

    const spawn = require('child_process').spawn;
    const ls = spawn('ls', ['-lh', '/usr']);
    const EventEmitter = require('events');
    const util = require('util');
    
    function MyEmitter() {
        EventEmitter.call(this);
    }
    util.inherits(MyEmitter, EventEmitter);
    
    const myEmitter = new MyEmitter();
    ls.stderr.on('data', (data) => {
        myObj.data = true;
        myEmitter.emit('data-changed', myObj);
    });