cssAudio - Activefile-genericCSS - ActiveGeneric - ActiveHTML - ActiveImage - ActiveJS - ActiveSVG - ActiveText - Activefile-genericVideo - ActiveLovehtmlicon-new-collectionicon-personicon-teamlog-outoctocatpop-outspinnerstartv

Pen Settings

CSS Base

Vendor Prefixing

Add External CSS

These stylesheets will be added in this order and before the code you write in the CSS editor. You can also add another Pen here, and it will pull the CSS from it. Try typing "font" or "ribbon" below.

Quick-add: + add another resource

Add External JavaScript

These scripts will run in this order and before the code in the JavaScript editor. You can also link to another Pen here, and it will run the JavaScript from it. Also try typing the name of any popular library.

Quick-add: + add another resource

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

            
              <nav class="navbar navbar-dark bg-inverse">
  <div class="container">
    <div class="row">
      <a class="navbar-brand" href="#">Pub/Sub in React</a>
    </div>
  </div>
</nav>
<br />
<div class="container">

  <div class="row">
    <div id="pub-1" class="col-xs-12"></div>
  </div>
  <div class="row">
    <div id="sub-1" class="col-xs-6"></div>
    <div id="sub-2" class="col-xs-6"></div>
  </div>
</div>
            
          
!
            
              //== Pub/Sub snippet
var events = (function(){
  var topics = {};
  var hOP = topics.hasOwnProperty;

  return {
    subscribe: function(topic, listener) {
      // Create the topic's object if not yet created
      if(!hOP.call(topics, topic)) topics[topic] = [];

      // Add the listener to queue
      var index = topics[topic].push(listener) -1;

      // Provide handle back for removal of topic
      return {
        remove: function() {
          delete topics[topic][index];
        }
      };
    },
    publish: function(topic, info) {
      // If the topic doesn't exist, or there's no listeners in queue, just leave
      if(!hOP.call(topics, topic)) return;

      // Cycle through topics queue, fire!
      topics[topic].forEach(function(item) {
            item(info != undefined ? info : {});
      });
    }
  };
})();

//== React Examplo
const { Component } = React;

//== Component that will publish to 'test' channel
class Pub extends Component {
    constructor() {

        super();

        this.state = {
            inputVal: ''
        };
    }

    handleChange(e) {

        // $.publish('test', { msg: e.target.value });
        this.setState({ inputVal: e.target.value });
    }

    handleClick() {

        events.publish('test', { msg: this.state.inputVal });
    }

    render() {

        const { inputVal } = this.state;

        return (
            <div className="card card-inverse card-primary text-xs-center">
                <div className="card-header">Component 1</div>
                <div className="card-block">
                    <h4 className="card-title">Whatever you provide here, will be sent to the subscribers.</h4>
                    <form onSubmit={ e => e.preventDefault() }>
                      <div className="form-group">
                          <input type="text" className="form-control" onChange={ this.handleChange.bind(this) } defaultValue={ inputVal } />
                      </div>
                      <button type="submit" className="offset-xs-5 col-xs-2 btn btn-secondary" onClick={ this.handleClick.bind(this) }>Send</button>
                  </form>
                </div>
                <div className="card-footer">
                    This is the component that Publishes
                </div>
            </div>
        );
    }
}

//== Component that will subscribe to 'test' channel
class Sub extends Component {
    constructor() {

        super();

        // Init state
        this.state= {
            msg: null
        };

        // Subscribing to channel
        this.handleSubscribe();
    }

    handleSubscribe() {

        this.subscription = events.subscribe('test', this.handleData.bind(this));
        this.setState({ data: 'subscribed!' });
    }

    handleUnsubscribe() {

        this.subscription.remove();
        this.setState({ data: 'not subscribed' });
    }

    handleData(data) {

        this.setState({ data: data.msg });
    }

    render() {

        const { data } = this.state;
        const style = {
            'background-color': '#333',
            'border-color': '#333'
        };

        return (
            <div className="card card-inverse text-xs-center" style={ style }>
                <div className="card-header" style={ style }>Component 2</div>
                <div className="card-block">
                    <p className="card-text">Data in state:</p>
                    <p style={ { color: '#ddd' } }>{ `{ ${data} }` }</p>

                    <p className="card-text">Action buttons:</p>
                    <div className="row">
                      <button className="col-xs-6 btn btn-primary" onClick={ this.handleSubscribe.bind(this) }>Subscribe</button>
                      <button className="col-xs-6 btn btn-danger" onClick={ this.handleUnsubscribe.bind(this) }>Unsubscribe</button>
                    </div>
                </div>
                <div className="card-footer" style={ style }>
                    This is a subscriber component
                </div>
            </div>
        );
    }
}

//== Component that will subscribe to 'test' channel
class Sub2 extends Component {
    constructor() {

        super();

        // Init state
        this.state= {
            msg: null
        };

        // Subscribing to channel
        this.handleSubscribe();

    }

    handleData(data) {

        this.setState({ data: data.msg });
    }

    handleSubscribe() {

        this.subscription = events.subscribe('test', this.handleData.bind(this));
        this.setState({ data: 'subscribed!' });
    }

    handleUnsubscribe() {

        this.subscription.remove();
        this.setState({ data: 'not subscribed' });
    }

    render() {

        const { data } = this.state;
        const style = {
            'background-color': '#333',
            'border-color': '#333'
        };

        return (
            <div className="card card-inverse text-xs-center" style={ style }>
                <div className="card-header" style={ style }>Component 3</div>
                <div className="card-block">
                    <p className="card-text">Data in state:</p>
                    <p style={ { color: '#ddd' } }>{ `{ ${data} }` }</p>

                    <p className="card-text">Action buttons:</p>
                    <div className="row">
                      <button className="col-xs-6 btn btn-primary" onClick={ this.handleSubscribe.bind(this) }>Subscribe</button>
                      <button className="col-xs-6 btn btn-danger" onClick={ this.handleUnsubscribe.bind(this) }>Unsubscribe</button>
                    </div>
                </div>
                <div className="card-footer" style={ style }>
                    This is a subscriber component
                </div>
            </div>
        );
    }
}

//== Actual Rendering from React
ReactDOM.render(
    <Pub />,
    document.getElementById('pub-1')
);
ReactDOM.render(
    <Sub />,
    document.getElementById('sub-1')
);
ReactDOM.render(
    <Sub2 />,
    document.getElementById('sub-2')
);


            
          
!
999px
Close

Asset uploading is a PRO feature.

As a PRO member, you can drag-and-drop upload files here to use as resources. Images, Libraries, JSON data... anything you want. You can even edit them anytime, like any other code on CodePen.

Go PRO

Loading ..................

Console