簡體   English   中英

在node.js中,如何告知發出事件的來源?

[英]In node.js, how to tell the source of an emitted event?

有沒有辦法告訴事件處理程序內部回調哪個函數和/或對象發出(調用)事件?

這是一個示例程序:

var EventEmitter, ee, rand, obj;
EventEmitter = require("events").EventEmitter;

ee = new EventEmitter();
ee.on('do it', cFunc);

obj = {
    maybeMe:    true,
    emitting:   function() {
                    ee.emit('do it');
                }
}
function aFunc() {
    ee.emit('do it');
}
function bFunc() {
    ee.emit('do it');
}
function cFunc() {
    console.log('Who called me to do it?  aFunc or bFunc or obj (obj.emitting)?');
}

rand = Math.random(); 

if (rand < .3) {
    aFunc();
} else if (rand < .6) {
    bFunc();
} else {
    obj.emitting();
}

另外,如果發出的事件的源來自內置模塊中的node.js,則另一種用途。 例如,'錯誤'事件。 如果我使用公共回調進行錯誤處理,那么這個回調是否可以知道是誰發出了調用它的事件?

這是您的特定示例的解決方案:

function cFunc() {
    var caller = new Error().stack.split("\n")[3].trim().substring(3).split(" (")[0];
    console.log('Who called me to do it?  aFunc or bFunc or obj (obj.emitting)?');
    console.log(caller);
}

說明

我們使用Error來獲取當前堆棧( 更多信息 )。 堆棧表示為字符串 - 第四行表示調用函數。

是的, this在事件監聽器函數中將引用發出事件的EventEmitter對象。 一般來說,使用this可能不是一個好主意,因為它可能不代表您感興趣的完整對象。相反,您可以通過閉包引用原始對象,如下所示:

object.on('event', function() {
  var value = object.value;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM