【问题标题】:EventEmmitter: access the event from within the callbackEventEmmitter:从回调中访问事件
【发布时间】:2013-12-01 14:44:54
【问题描述】:

我可以从触发事件时执行的回调中访问事件的名称吗?

考虑以下示例,其中我对两个不同的事件有相同的回调 (handleEvent)。现在我想根据触发其执行的事件在回调中添加条件语句。这可能吗?

obj.on('start', handleEvent);
obj.on('stop', handleEvent);

function handleEvent() {
       // how can I check here if the event that triggers the execution of handleEvent is 'start' or 'stop'

}

我现在做的是用 'emit' 两次传递事件 - 这似乎工作正常,但我不喜欢写两次:

obj.emit('start', 'start', handleEvent);

【问题讨论】:

    标签: node.js eventemitter


    【解决方案1】:

    试试EventEmitter2:

    var EventEmitter = require('eventemitter2').EventEmitter2
    var emitter = new EventEmitter
    
    emitter.on('test', onEvent)
    emitter.emit('test')
    
    function onEvent() {
      console.log(this.event)
    }
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

      obj.on('start', handleEvent.bind({ event: 'start' }));
      obj.on('stop', handleEvent.bind({ event: 'stop' }));
      
      function handleEvent() {
          if(this.event == 'start') { ///
      }
      

      【讨论】:

        猜你喜欢
        • 2015-10-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-14
        • 2019-09-05
        • 2021-06-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多