实现一个带有 once 的 pubsub 类.使用 JavaScript 实现
时间: 2023-02-25 21:36:28 浏览: 73
前端项目-pubsub-js.zip
以下是 JavaScript 代码实现一个带有 "once" 功能的 pubsub 类:
```
class Pubsub {
constructor() {
this.subscribers = {}
}
subscribe(event, callback) {
if (!this.subscribers[event]) {
this.subscribers[event] = []
}
this.subscribers[event].push(callback)
}
once(event, callback) {
const wrapper = (...args) => {
callback(...args)
this.off(event, wrapper)
}
this.subscribe(event, wrapper)
}
off(event, callback) {
if (!this.subscribers[event]) {
return
}
this.subscribers[event] = this.subscribers[event].filter(
item => item !== callback
)
}
publish(event, ...args) {
if (!this.subscribers[event]) {
return
}
this.subscribers[event].forEach(callback => callback(...args))
}
}
```
使用方法:
```
const pubsub = new Pubsub()
const callback = (data) => {
console.log(`Received data: ${data}`)
}
pubsub.subscribe('event', callback)
pubsub.publish('event', 'Hello World!')
// Output: Received data: Hello World!
pubsub.once('event', (data) => {
console.log(`Received data once: ${data}`)
})
pubsub.publish('event', 'Hello World!')
// Output:
// Received data: Hello World!
// Received data once: Hello World!
pubsub.publish('event', 'Hello World!')
// Output:
// Received data: Hello World!
```
这个 pubsub 类提供了 "subscribe"、"once"、"off" 和 "publish" 四个方法,它们分别用于订阅、只订阅一次、取消订阅和发布事件。
阅读全文