type-pubsub
Version:
TypeScript decorators implementing the Publish/Subscribe pattern for Node.js and browser
46 lines (45 loc) • 1.5 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Channel = void 0;
var Channel = /** @class */ (function () {
function Channel() {
this.subscriptions = new Map();
}
Channel.prototype.publish = function (message, data) {
var _this = this;
var handlers = this.subscriptions.get(message);
if (handlers) {
handlers.forEach(function (handler) {
handler(data, message, _this, handler);
});
}
};
Channel.prototype.subscribe = function (message, handler) {
var handlers = this.subscriptions.get(message);
if (!handlers) {
handlers = [];
this.subscriptions.set(message, handlers);
}
handlers.push(handler);
};
Channel.prototype.unsubscribe = function (message, handler) {
var handlers = this.subscriptions.get(message);
if (handlers) {
handlers = handlers.filter(function (x) { return x !== handler; });
if (handlers.length) {
this.subscriptions.set(message, handlers);
}
else {
this.subscriptions.delete(message);
}
}
};
/**
* Unregister all subscriptions for the channel
*/
Channel.prototype.unsubscribeAll = function () {
this.subscriptions.clear();
};
return Channel;
}());
exports.Channel = Channel;