Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- let pubSubInstance;
- /**
- * The PubSub class servers as a singleton,
- * it's used by the EventDispatcher class
- * (don't instantiate this class directly)
- */
- class PubSub {
- constructor() {
- if (!pubSubInstance) {
- this.subjects = {};
- this.hOP = this.subjects.hasOwnProperty;
- pubSubInstance = this;
- }
- return pubSubInstance;
- }
- /**
- *
- * @param {string} topic The event name
- * @param {function} callback Function to bind to the event
- * @return {PubSub} The PubSub singleton instance
- */
- on(topic, callback) {
- const { subjects, hOP } = this;
- if (!hOP.call(subjects, topic)) {
- subjects[topic] = [];
- }
- subjects[topic].push(callback);
- return this;
- }
- /**
- *
- * @param {string} topic The event name
- * @param {function} callback Function to un-bind from the event
- * @return {PubSub} The PubSub singleton instance
- */
- off(topic, callback) {
- const { subjects } = this;
- if (subjects[topic] && subjects[topic].length) {
- const idx = subjects[topic].indexOf(callback);
- if (idx !== -1) {
- subjects[topic].splice(idx, 1);
- }
- }
- return this;
- }
- /**
- *
- * @param {string} topic The event name
- * @param {object} data Extra data to pass with the event
- * @return {PubSub|null} The PubSub singleton instance
- */
- trigger(topic, data) {
- const { subjects, hOP } = this;
- if (!hOP.call(subjects, topic)) {
- return null;
- }
- subjects[topic].forEach((entry) => {
- if (entry) {
- entry(data !== undefined ? data : {});
- }
- });
- return this;
- }
- }
- /**
- * The EventDispatcher class servers as a global event dispatcher,
- * it uses the PubSub singleton class
- */
- export default class EventDispatcher {
- constructor() {
- this.pubSub = new PubSub();
- }
- /**
- *
- * Please read the {@link PubSub.on} specs
- */
- on(...args) {
- return this.pubSub.on(...args);
- }
- /**
- *
- * Please read the {@link PubSub.off} specs
- */
- off(...args) {
- return this.pubSub.off(...args);
- }
- /**
- *
- * Please read the {@link PubSub.trigger} specs
- */
- trigger(...args) {
- return this.pubSub.trigger(...args);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement