观察者模式和发布订阅模式

文章目录

观察者模式

Subject 和 Observer 直接绑定,中间无媒介。如点击事件,事件直接和按钮进行绑定。

发布订阅模式

Publisher 和 Observer 相互不认识,中间有媒介。如在 A 组件中绑定一个事件,在 B 组件中触发这个事件,这个两个组件相隔十万八千里互补认识,那么就通过中间event这个媒介来通讯。

发布订阅模式需要在代码中触发 emit ,而观察者模式没有 emit

手写观察者模式

jsx 复制代码
import React, { useState, useEffect } from 'react';

// 观察者函数
const observer = (newValue) => {
  console.log(`Subject changed to ${newValue}`);
};
const SubjectComponent = () => {
  // 使用useState创建一个状态变量
  const [subject, setSubject] = useState('Initial Value');
  // 使用useEffect来模拟观察者模式
  useEffect(() => {
    // 当subject变化时,调用观察者函数
    observer(subject); 
  }, [subject]); // 依赖数组中包含subject,这样每当subject变化时,useEffect都会执行
  // 更新subject的方法
  const updateSubject = () => {
    setSubject('Updated Value');
  };
  return (
    <div>
      <p>Subject: {subject}</p>
      <button onClick={updateSubject}>Update Subject</button>
    </div>
  );
};

export default SubjectComponent;

手写发布订阅模式

jsx 复制代码
// EventBus.js
import { createContext, useContext, useState } from 'react';

const EventBusContext = createContext();

export const EventBusProvider = ({ children }) => {
  const [events, setEvents] = useState({});

  const subscribe = (eventName, callback) => {
    if (!events[eventName]) {
      setEvents((prevEvents) => ({
        ...prevEvents,
        [eventName]: [],
      }));
    }
    setEvents((prevEvents) => ({
      ...prevEvents,
      [eventName]: [...prevEvents[eventName], callback],
    }));
  };

  const publish = (eventName, data) => {
    if (events[eventName]) {
      events[eventName].forEach((callback) => callback(data));
    }
  };

  return (
    <EventBusContext.Provider value={{ subscribe, publish }}>
      {children}
    </EventBusContext.Provider>
  );
};

export const useEventBus = () => useContext(EventBusContext);
相关推荐
@大迁世界2 分钟前
Promise.all 与 Promise.allSettled:一次取数的小差别,救了我的接口
开发语言·前端·javascript·ecmascript
知识分享小能手4 分钟前
微信小程序入门学习教程,从入门到精通,项目实战:美妆商城小程序 —— 知识点详解与案例代码 (18)
前端·学习·react.js·微信小程序·小程序·vue·前端技术
DoraBigHead17 分钟前
React 中的代数效应:从概念到 Fiber 架构的落地
前端·javascript·react.js
今天头发还在吗43 分钟前
【框架演进】Vue与React的跨越性变革:从Vue2到Vue3,从Class到Hooks
javascript·vue.js·react.js
渣哥1 小时前
从 AOP 到代理:Spring 事务注解是如何生效的?
前端·javascript·面试
toobeloong1 小时前
Electron 从低版本升级到高版本 - 开始使用@electron/remote的改造教程
前端·javascript·electron
悠哉摸鱼大王1 小时前
前端获取设备视频流踩坑实录
前端·javascript
铅笔侠_小龙虾1 小时前
深入理解 Vue.js 原理
前端·javascript·vue.js
你的眼睛會笑1 小时前
vue3 使用html2canvas实现网页截图并下载功能 以及问题处理
前端·javascript·vue.js