sdc-pubsub
Version:
Publish Subscribe library using post message for sdc plugins
95 lines • 4.13 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var BasePubSub = /** @class */ (function () {
function BasePubSub(pluginId) {
this.subscribers = new Map();
this.eventsCallbacks = [];
this.eventsToWait = new Map();
this.clientId = pluginId;
this.lastEventNotified = '';
this.onMessage = this.onMessage.bind(this);
window.addEventListener('message', this.onMessage);
}
BasePubSub.prototype.register = function (subscriberId, subscriberWindow, subscriberUrl) {
var subscriber = {
window: subscriberWindow,
locationUrl: subscriberUrl || subscriberWindow.location.href
};
this.subscribers.set(subscriberId, subscriber);
};
BasePubSub.prototype.unregister = function (subscriberId) {
this.subscribers.delete(subscriberId);
};
BasePubSub.prototype.on = function (callback) {
var functionExists = this.eventsCallbacks.find(function (func) {
return callback.toString() === func.toString();
});
if (!functionExists) {
this.eventsCallbacks.push(callback);
}
};
BasePubSub.prototype.off = function (callback) {
var index = this.eventsCallbacks.indexOf(callback);
this.eventsCallbacks.splice(index, 1);
};
BasePubSub.prototype.notify = function (eventType, eventData) {
var eventObj = {
type: eventType,
data: eventData,
originId: this.clientId
};
this.subscribers.forEach(function (subscriber, subscriberId) {
subscriber.window.postMessage(eventObj, subscriber.locationUrl);
});
this.lastEventNotified = eventType;
return {
subscribe: function (callbackFn) {
var _this = this;
if (this.subscribers.size !== 0) {
var subscribersToNotify_1 = Array.from(this.subscribers.keys());
var checkNotifyComplete_1 = function (subscriberId) {
var index = subscribersToNotify_1.indexOf(subscriberId);
subscribersToNotify_1.splice(index, 1);
if (subscribersToNotify_1.length === 0) {
callbackFn();
}
};
this.subscribers.forEach(function (subscriber, subscriberId) {
if (_this.eventsToWait.has(subscriberId) &&
_this.eventsToWait.get(subscriberId).indexOf(eventType) !== -1) {
var actionCompletedFunction_1 = function (actionCompletedEventData, subId) {
if (subId === void 0) { subId = subscriberId; }
if (actionCompletedEventData.type === 'ACTION_COMPLETED') {
checkNotifyComplete_1(subId);
}
_this.off(actionCompletedFunction_1);
};
_this.on(actionCompletedFunction_1);
}
else {
checkNotifyComplete_1(subscriberId);
}
});
}
else {
callbackFn();
}
}.bind(this)
};
};
BasePubSub.prototype.isWaitingForEvent = function (eventName) {
return Array.from(this.eventsToWait.values()).some(function (eventsList) {
return eventsList.indexOf(eventName) !== -1;
});
};
BasePubSub.prototype.onMessage = function (event) {
if (this.subscribers.has(event.data.originId)) {
this.eventsCallbacks.forEach(function (callback) {
callback(event.data, event);
});
}
};
return BasePubSub;
}());
exports.BasePubSub = BasePubSub;
//# sourceMappingURL=base-pubsub.js.map