2017-10-07 96 views
1

在一個地方,我們使用eventEmitter來生成事件。其實這是很常見的方式。發佈/訂閱模式中的參數如何工作?

eventEmitter.emit('started', data, date); 

在其他地方,我們試圖捕捉它。使用箭頭功能時,一切都非常清晰。 「數據」和「日期」被傳遞給函數作爲參數

someInstanse.event.on('started', (data, date) => { 
    //crazy stuff here 
}) 

但如何notaion其實作品?我們判斷3個ARGS與發射器,現在我們真的只有事件串和函數,而不是

someInstance.event.on('started', function(data, date) { 
}); 

我想這將箭頭功能之前,它調用匿名函數

+0

打開Node文檔並讀取發出方法將參數傳遞給偵聽器。另外每個emitter.on(eventName,listener)意味着監聽器是一個回調函數。所以現在不是問題。 –

+0

你對數據如何傳遞給回調函數感到困惑嗎?或者這個均衡器如何在引擎蓋下工作? – Chang

+0

是的,現在我知道如何制定它。我不知道爲什麼在客戶端調用'emit'並不會在服務器上導致'emit'。根據發佈/訂閱模式,每個發佈迭代通過偵聽器函數並執行它們,或者如果帶有句柄的數組未定義,則返回false。我試圖Socket.IO庫,所以它只能鉤住由服務器本身調用的'emits'。 –

回答

1

這是典型發佈的唯一途徑/訂閱設計模式。這真的取決於emit以及用戶如何對事件做出反應。

基本上,在發佈函數中,你想調用每個訂閱者(on)函數,提供與publish(emit)的信息。下面只是一些僞代碼。

function publish(type, ...args) { 
    // for each of the subscribers of that type 
    for (let i = 0; i < pubsub[type].length; i++) { 
     // you could do (this provides the listener with type) 
     subscribers[i](type, ...args) 
     // or you could do (the subscriber doesn't know the type) 
     subscriber[i](...args) 
    } 
} 

我在github上寫了一個縮小的pub/sub模式,如果你想看看。我認爲這對幫助你理解這個問題非常有幫助。 https://github.com/thomasyimgit/pubsub/blob/master/index.js