JSFiddle - React, Tailwind, and code Playground
by canree
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.content();
$scope.$on('newmsg', function() {
$scope.$apply();
});
});
// 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.content = function() {
return this.messages;
};
this.append = function(data) {
this.messages.push(data);
_broadcastNewMessage();
};
function _broadcastNewMessage() {
$rootScope.$broadcast('newmsg');
}
});
// 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"
this.init = function() {
pubSubFake.subscribe(function(data) {
self.notifyCallback(data);
});
}
this.subscribe = function(callback, caller) {
self.notifyCallback = function(data) {
callback.call(caller, data);
};
}
});
app.run(function(inbox, pubsub) {
pubsub.init();
pubsub.subscribe(inbox.append, inbox);
});
// *******************************
// 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();