UNPKG

publisher-subscriber-ts

Version:
1 lines 2.16 kB
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var uuid=require("uuid"),Subscriber=function(){function e(e,i){this._callBack=e,this._id=uuid.v4(),this._topicName=i}return Object.defineProperty(e.prototype,"callBack",{get:function(){return this._callBack},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"id",{get:function(){return this._id},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"topicName",{get:function(){return this._topicName},enumerable:!1,configurable:!0}),e}(),Topic=function(){function e(e){this._topicName=e,this._subscriberList=new Array}return e.prototype.publish=function(e){this._currentValue=e;for(var i=0,t=this._subscriberList;i<t.length;i++){var r=t[i];this.emitValueToSubscriber(r)}},e.prototype.subscribe=function(e,i){var t=new Subscriber(e,this._topicName);return i.getLastValue&&this._currentValue&&this.emitValueToSubscriber(t),this._subscriberList.push(t),t},e.prototype.unsubscribe=function(e){if(e&&e.id){var i=this._subscriberList.findIndex(function(i){return i.id===e.id});i>-1&&this._subscriberList.splice(i,1)}},Object.defineProperty(e.prototype,"topicName",{get:function(){return this._topicName},enumerable:!1,configurable:!0}),e.prototype.emitValueToSubscriber=function(e){this._currentValue&&e.callBack.call(this,this._currentValue)},e}(),Publisher=function(){function e(){}return e.createTopic=function(e){var i=new Topic(e);return this._topicMap.set(e,i),i},e.subscribeTopic=function(e,i){var t,r;if(!e.topicName)throw new Error("Topic name cannot be empty or null while subscribing");if(!this._topicMap.has(e.topicName))throw new Error("Cannot find topic with name: "+e.topicName+". Please create one and then subscribe.");if(this._topicMap)return null===(r=null===(t=this._topicMap)||void 0===t?void 0:t.get(e.topicName))||void 0===r?void 0:r.subscribe(i,e)},e.unsubscribeTopic=function(e){var i,t;if(!this._topicMap.has(e.topicName))throw new Error("Cannot find topic with name: "+e.topicName);null===(t=null===(i=this._topicMap)||void 0===i?void 0:i.get(e.topicName))||void 0===t||t.unsubscribe(e)},e._topicMap=new Map,e}();exports.Publisher=Publisher;