publish/subscribe 模式中的参数如何工作?
How do arguments in publish/subscribe pattern work?
我们在一处使用 eventEmitter 来生成事件。其实这是很常见的方式。
eventEmitter.emit('started', data, date);
在另一个地方我们试着抓住它。使用箭头函数时一切都非常清楚。 'data' 和 'date' 作为参数传递给函数
someInstanse.event.on('started', (data, date) => {
//crazy stuff here
})
但是这个概念实际上是如何工作的呢?我们用发射器确定了 3 个参数,现在我们实际上只有事件字符串和一个函数
someInstance.event.on('started', function(data, date) {
});
我想在添加箭头函数之前它是调用匿名函数的唯一方法
这是典型的 publish/subscribe 设计模式。这实际上取决于 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
我们在一处使用 eventEmitter 来生成事件。其实这是很常见的方式。
eventEmitter.emit('started', data, date);
在另一个地方我们试着抓住它。使用箭头函数时一切都非常清楚。 'data' 和 'date' 作为参数传递给函数
someInstanse.event.on('started', (data, date) => {
//crazy stuff here
})
但是这个概念实际上是如何工作的呢?我们用发射器确定了 3 个参数,现在我们实际上只有事件字符串和一个函数
someInstance.event.on('started', function(data, date) {
});
我想在添加箭头函数之前它是调用匿名函数的唯一方法
这是典型的 publish/subscribe 设计模式。这实际上取决于 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