2016-12-24 14 views
1

我想從一個開源項目中瞭解一些代碼片段,我不明白什麼意思是將EventEmitter.emit與星號'*'作爲事件名稱。NodeJS EventEmitter:使用事件名稱作爲「*」(星號)

在某些庫(如JQuery)中,作爲事件名稱的'*'表示「所有事件」。

這是什麼意思在EventEmitter的上下文中?

我試圖在此項目中找到'*'事件的監聽者,但沒有運氣。

class BlaBla extends EventEmitter { 

    methodCall(event){ 
     this.emit("*", {event}); // <- what does this mean ??? 
    } 
} 
+0

你可以發佈一個鏈接到這個項目? – nem035

+0

@ nem035 - 感謝您的幫助!項目鏈接 - github.com/liangzeng/cqrs –

回答

0

this.emit("*", {event});意味着調用EMIT()方法將執行所有與該上方法進行註冊的功能。

+0

查看[代碼](https://github.com/nodejs/node/blob/master/lib/events.js#L136)並在REPL中運行它顯示這裏不是這種情況。 – nem035

0

使用'*'作爲事件名稱沒有特殊效果,它表現爲正常事件。

你可以看看event emitter code,看到唯一的特別事件名稱爲:

示例(repl.it code

const { 
    EventEmitter 
} = require('events'); 

class BlaBla extends EventEmitter { 

    methodCall(stuff) { 
    this.emit("*", { 
     stuff // <-- this gets passed as an argument to the handler for the '*' event 
    }); 
    } 
} 

const b = new BlaBla(); 

b.on('a', (...args) => console.log('nope', ...args)); // <-- this doesn't run 
b.on('b', (...args) => console.log('nope', ...args)); // <-- this doesn't run 
b.on('*', (...args) => console.log('this gets called', ...args)); // <-- This runs 

b.methodCall('this gets passed down'); 

輸出

this gets called { stuff: 'this gets passed down' } 

如果在這個特定的項目時this.emit('*')被稱爲所有事件處理程序被調用,他們可能手工做這個。

下面是它是如何做一個簡單的例子:

const eventNames = ['a', 'b', 'c']; 

this.on('*',() => 
    eventNames.forEach(event => this.emit(event)) 
); 
相關問題