一些数据后创建事件对象

Create events object after some data was

我有几个事件需要通过附加事件来监听并传递对象:

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
});

例如,在每个事件中,我想发出 我的事件 并使用 属性 发送对象。例如,用我的对象引发 myEvent,每个后续事件都会在我的对象中更新 属性,如数据、关闭、打开

假设这是我的对象

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

我该怎么做?

您可以使用 Event object/API 创建事件。

创建自定义事件(copy/paste 来自链接源)

var event = new Event('build');

// Listen for the event.
elem.addEventListener('build', function (e) { ... }, false);

// Dispatch the event.
elem.dispatchEvent(event);

您可能还想了解文档的下一部分,它可以让您向事件添加自定义数据:

var event = new CustomEvent('build', { 'detail': elem.dataset.time });

function eventHandler(e) {
  console.log('The time is: ' + e.detail);
}

这应该适用于除 IE11 之外的所有现代浏览器。如果您查看文档,则会有一个更长的示例显示 work-around 适用于旧版浏览器。

显而易见的方法是编写您自己的小事件 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
});

编辑

由于您使用的是 Node,因此可以使用 EventEmitter,其工作方式与此类似:

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);
});