DEV Community

Discussion on: Singleton design pattern. JS/TS Examples.

Collapse
 
subztep profile image
Andras Serfozo

I haven't found any use cases in Front End development where singleton design pattern would be really helpful

I implemented singleton recently in TS for a special use case, and tbh I still have no idea how could I resolve it without - probably pointless - significant code refactoring.

So, it happens during development only. The stack is Vite and Vue with hot module replacement, also Three.js as a big background canvas.

First create an Object3D and add to the scene. Update the code anywhere, save it, the HMR kicks in and update the DOM alongside the 3D canvas nicely, but my object gets duplicated. Another save, another unwanted instance and so on.

I created a module just to keep a "global" array persistent for holding my single 3d object but didn't work, duplicates for each re-run. However, after a while I made a proper singleton class instance, loaded with a Map as my object container and voila, no more duplication, works like a proper session, keep any object instances unchanged. I'm not really sure why.

Collapse
 
ryabinin profile image
Vlad R

interesting, thanks for sharing your use case, Andras!