javascript - Create events object after some data was -


i've several events need listen additional event , pass object:

const spawn = require('child_process').spawn; const ls = spawn('ls', ['-lh', '/usr']);  ls.stderr.on('data', (data) => {   myobj.data = true   //here need raise event property data });  ls.on('close', (code) => {   myobj.close = true   //here need raise event property close }); 

for example inside of every event want emit my events , send object property. example raise myevent object , every following event update property in object data,close,open

let's object

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

how can this?

the obvious way code 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, can use eventemitter, works in 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); }); 

Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -