在一个地方,我们使用 eventEmitter 来生成事件。其实这是很常见的方式。
eventEmitter.emit('started', data, date);
在另一个地方我们试图捕获它。使用箭头函数时一切都非常清楚。 “数据”和“日期”作为参数传递给函数
someInstanse.event.on('started', (data, date) => {
//crazy stuff here
})
但是这个概念实际上是如何工作的呢?我们用发射器确定了 3 个参数,现在我们实际上只有事件字符串和一个函数
someInstance.event.on('started', function(data, date) {
});
我想在添加箭头函数之前,这是调用匿名函数的唯一方法
最佳答案
这是典型的发布/订阅设计模式。它实际上取决于 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 中写了一个缩小的发布/订阅模式。我认为帮助您理解这个问题非常有帮助。 https://github.com/thomasyimgit/pubsub/blob/master/index.js
关于javascript - 发布/订阅模式中的参数如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46615926/