PubSub

  1. Passing values (communication) between sibling components

    Passing values between parent and child components: With the help of props, the child passes a function to the parent with props, and the child component calls the function and passes parameters.

    Passing values between sibling components: message subscription and publishing mechanism.


    PubSub is not only suitable for passing values between sibling components, but also for passing values between any components, especially for passing messages in multi-level hierarchical components, because it doesn’t matter where the components are.


  2. Message Subscription and Publishing

    Tool library: PubSubJS (PubSub is the abbreviation of Publish and Subscribe)

    Download: npm install pubsub-js --save


    Steps for usage:

    1. Introduce import PubSub from 'pubsub-js' (the repository name of a technology is different from the npm name, because of the npm specification)

    2. Subscribe PubSub.subscribe{'delete', function(data){}};

    3. Publish a message PubSub.publish('delete', data)


  3. PubSub use

    1. Subscribe messages in components that need to receive data

      1
      2
      3
      4
      var mySubscriber = function(msg, data){ //Parameter 1 is the message name (useless, available _, placeholder), and parameter 2 is the data.
      console.log(msg, data)
      }
      var token = PubSub.subscribe("My Topic", mySubscriber); //Parameter 1 is the message name, and parameter 2 is the callback function that will be called when someone publishes a message. Assigned to token is used when unsubscribing later.

      mySubscriber is usually written directly in the PubSub.subscribe method, and is usually subscribed after the component is mounted. After the code is simplified:

      1
      2
      3
      4
      5
      componentDidMount(){
      let token = PubSub.subscribe("My Topic 1", (_, data) => {
      console.log(data);
      })
      }

      Cancel subscription: usually before the component is unloaded.

      1
      2
      3
      componentWillUnmount(){
      PubSub.unsubscribe(token)
      }

    2. Post a message in the component that generates the data

      1
      PubSub.publish("My Topic", 'hello world!'); //Parameter 1 is the message name, parameter 2 is the sent data, usually {}

Share