How to write a singleton service for a Vue3 component javascript

  javascript, service, singleton, vuejs3

I have a tooltip control I’ve written that works very nicely in Vue 3, but I need a mechanism to fire off to all other instances to tell them to close. There are delays on close, so I’m occasionally getting two tooltips to show up at the same time.

This method, which was a crutch I’ve used in the past, is not allowed by the compiler / build tools. I can full well understand why, but I don’t know the right way:

tooltipManager: function() {
  if (!window.TooltipManager) {
    function tooltipManager() { 
     
     let _data = {
        tooltipIndex: 0,
        callbacks: {}
      };

      return {
  
        register: function (callback) {
          let id = "tooltip_" + _data.tooltipIndex;
          _data.tooltipIndex++;
          _data.callbacks[id] = callback;
          return id;
        },

        closeOpenPopups: function (id) {
          Object.keys(_data.callbacks).forEach(key => {
            if (id !== key) {
              _data.callbacks[key]();
            }
          });
        },

        destroy: function (id) {
          delete _data.callbacks[id];
        }
      
      };

    }

    window.TooltipManager = tooltipManager();
  }
  return window.TooltipManager()
},

The first thing I tried but didn’t work was a service which I imported:

export default class TooltipManager {

  constructor() {
    if(! TooltipManager.instance){
      this._data = {
        tooltipIndex: 0,
        callbacks: {}
      };
    } 
  }

  register (callback) {
    let id = "tooltip_" + this._data.tooltipIndex;
    this._data.tooltipIndex++;
    this._data.callbacks[id] = callback;
    return id;
  }

  closeOpenPopups(id) {
    Object.keys(this._data.callbacks).forEach(key => {
      if (id !== key) {
        this._data.callbacks[key]();
      }
    });
  }

  destroy(id) {
    delete this._data.callbacks[id];
  }

}

Source: Ask Javascript Questions

LEAVE A COMMENT