在软件架构中,发布订阅是一种消息范式,消息的发送者(称为发布者)不会将消息直接发送给特定的接收者(称为订阅者)。而是将发布的消息分为不同的类别,无需了解哪些订阅者(如果有的话)可能存在。同样的,订阅者可以表达对一个或多个类别的兴趣,只接收感兴趣的消息,无需了解哪些发布者(如果有的话)存在。
{% endgallery %}emitter.on('test')就是相当于订阅者,去消息中心订阅自己感兴趣的消息。emitter.off('test')取消订阅import React, { Component } from "react";
import emitter from "./eventbus";
class ClassTest extends Component {
handleChange = (param1, param2) => {
console.log(param1);
console.log(param2);
};
componentDidMount() {
emitter.on("test", this.handleChange);
}
componentWillUnmount() {
emitter.off("test", this.handleChange);
}
render() {
return <div>class test</div>;
}
}
export default ClassTest;emitter.emit('test')在这里是订阅者的身份,满足条件时,通过消息中心发布消息。此处的条件是点击这个 divimport React, { useState, useContext } from "react";
import emitter from "./eventbus";
const FuncTest = () => {
const handleChange = () => {
emitter.emit("test", "参数1", "参数2");
};
return <div onClick={handleChange}>B 组件</div>;
};
export default FuncTest;