import React from "react";
// 发布订阅
const login = {
list: {},
// 发布
publish(key) {
console.log('a', this.list[key]);
this.list[key].map(dt => {
dt()
})
},
// 订阅
ding(key, value) {
if (!this.list[key]) {
this.list[key] = []
}
this.list[key].push(value)
}
}
// 张波
function Xx() {
function abc() {
console.log('abc');
}
function xxx() {
console.log('xxx');
}
// 订阅
login.ding('pt', abc)
login.ding('pt', xxx)
}
Xx()
export default function Issue(props) {
const zhang = () => {
// 发布
login.publish('pt')
}
return (
<div>
<button onClick={zhang}>发布</button>
</div>
)
}
发布订阅模式
最新推荐文章于 2024-12-04 17:27:16 发布
文章展示了如何在React应用中实现一个简单的发布订阅模式。通过login对象,实现了publish方法来发布事件和ding方法来订阅事件。在Xx函数中订阅了pt事件,当调用publish方法时,会触发所有订阅的函数abc和xxx执行。
1172

被折叠的 条评论
为什么被折叠?



