作用:
也称之为消息队列模式,或者pubsub模式
发布者发布消息(也可以理解为调用某函数),订阅者会收到消息,并且发布者可以将一些参数传递给订阅者。
是一种常用的参数传递方法,经典的pubsub.js,vue2中的$bus等都是用的这种模式。
示例:
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>发布订阅模式</title>
</head><body><button onClick='subYou_vue()'>订阅尤大的vue技术专栏</button><button onClick='subYou_vite()'>订阅尤大的vite技术专栏</button><button onClick='cancelSubYou_vite()'>取消订阅尤大的vite技术专栏</button><hr><button onClick='pushVueBlog()'>尤大发vue技术贴</button><button onClick='pushViteBlog()'>尤大发vite技术贴</button><script>const Youyuxi = {blogMsg: {},//添加了某条订阅内容及后续需要处理的操作addSuber: (msg, callBack) => {if (!Youyuxi.blogMsg[msg]) {Youyuxi.blogMsg[msg] = []}Youyuxi.blogMsg[msg].push(callBack)},publishMsg: (msg, data) => {if (Youyuxi.blogMsg[msg]) {Youyuxi.blogMsg[msg].forEach(item => {item(msg, data)})}},deleteSuber:(msg)=>{if(Youyuxi.blogMsg[msg]){Youyuxi.blogMsg[msg] = null}}}const wjt = {getMsgHandler: (type, data) => {switch (type) {case 'vueBlogs':console.log('尤大发了一篇vue技术帖子,内容为' + data)breakcase 'viteBlogs':console.log('尤大发了一篇vite技术帖子,内容为' + data)break}},subYouyuxi: (title) => {Youyuxi.addSuber(title, wjt.getMsgHandler)},cancelViteBlog:(title)=>{Youyuxi.deleteSuber(title)}}//订阅尤大的vue技术栏const subYou_vue = () => {wjt.subYouyuxi('vueBlogs')}//订阅尤大的vite技术栏const subYou_vite = () => {wjt.subYouyuxi('viteBlogs')}//尤大发博客了const pushVueBlog = () => {Youyuxi.publishMsg('vueBlogs', '这是一篇vue3响应式原理的技术帖子')}const pushViteBlog = () => {Youyuxi.publishMsg('viteBlogs', '这是一篇vite构建原理的技术帖子')}const cancelSubYou_vite = ()=>{wjt.cancelViteBlog('viteBlogs')}</script>
</body></html>