【问题标题】:Create custom event in node js and update custome obj在节点 js 中创建自定义事件并更新自定义对象
【发布时间】:2016-01-17 07:33:05
【问题描述】:

我有一个监听一些事件的节点应用程序,我想创建我的自定义事件,该事件将使用此事件的属性更新一些对象,建议如何执行此操作?

假设我有两个文件,其中一个包含以下事件(常规事件) 和

这是 first.js

   //On open
    child.on('open', function (code) {
       //here raise my custom event with open property to the customObject
    });

    child.stdout.on('data', function (data) {
        //here raise my event with data property to the object
    });

    child.on('close', function (code) {
      //here raise my event with close property to the object
    });

    child.on('error', function (error) {
     //here raise my event with err property to the object
    });

在第二个文件 second.js 我想更新这个自定义对象 来自第一个文件/模块的值

second.js

var customObj ={
  data:false,
  open:true,
  close:true,
  error:error
}

【问题讨论】:

    标签: javascript node.js dom-events eventemitter


    【解决方案1】:

    在 second.js 中,导出如下方法:

    exports.updateData = function updateData(data) {
      customObj.data = data; // or whatever
    }
    

    然后在 first.js 事件监听器中调用这个方法,并使用适当的参数:

    var second = require("second.js");
    child.stdout.on('data', function (data) {
      second.updateData(data);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-28
      • 2011-09-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多