发布/订阅模式中的参数如何工作?

问题描述:

在一个地方,我们使用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'。 –

这是典型发布的唯一途径/订阅设计模式。这真的取决于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