JSFiddle - React, Tailwind, and code Playground

by mrajcok

HTML

<div ng-app="PubSubExample">

    <div ng-controller="InboxController">
        <h2>Incoming messages: {{msgCount}}</h2>
        <div>
            <ul>
                <li ng-repeat="msg in messages">{{msg}}</li>
            </ul>
        </div>
    </div>
    
    <!-- simulate something external from Angular, like sending message from PubSub -->
    <input id="send" type="button" onclick="pubSubFake.invoke()" value="Pretend PubSub sent message"/>
</div>

JavaScript

var app = angular.module('PubSubExample', []);

// I want my controller to have inbox service only as dependency
app.controller('InboxController', function($scope, inbox) {

    $scope.messages = inbox.messages;
});

// To abstract pubsub I want all other app "parts" to be dependent on inbox only
// and only inbox to be dependent on pubsub
app.service('inbox', function($rootScope, pubsub) {

    this.messages = [];

    this.append = function(data) {        
        this.messages.push(data);
        // an $http or $resource service will likely already 
        // call $apply(), so this probably won't be necessary
        $rootScope.$digest();
    };

    pubsub.subscribe(this.append, this);

});


// pubsub service
// as this is third-party one I'd like to be able to exchange it at any time
// with minor changes in app
app.service('pubsub', function() {
    var self = this;
    var pubSubFake = window.pubSubFake; // would be real PubSub client instance

    // start PubSub and bind to "channel"
    pubSubFake.subscribe(function(data) {
       self.notifyCallback(data);
    });        
    
    this.subscribe = function(callback, caller) {
        self.notifyCallback = function(data) {
            callback.call(caller, data);
        };
    }
});

// *******************************
// Pretend you are sth like PubSub
// send messages as if PubSub would send them
// *******************************

var PubSubFake = function() {
  this.count = 0;

  this.invoke = function() {
    this.count = this.count + 1;
    this.subscriber(this.count);
  };

  this.subscribe = function(callback) {
    this.subscriber = function(data) {
        callback(data);
    }
  };

};

var pubSubFake = new PubSubFake();