Is it a bad practice to use the requireJS module as a singleton?

前端 未结 2 1955
南方客
南方客 2020-12-04 23:42

I plan to use the following pattern to make use of the requireJS based module to act as a singleton. Please notice that classA returns an instance of type \

相关标签:
2条回答
  • 2020-12-05 00:20

    Will this come back to bite me at a later stage?

    I started out with the pattern of the accepted answer here, but my single-page JavaScript app morphed into a main thread and a web worker because it was doing a lot of calculations and the page was not responsive.

    As I moved some of the modules into the web worker, there was strange behavior. It took me a lot of time to figure it out, but I realized some of my requirejs modules (namely the singletons) were being loaded twice.

    What I found out was that if a singleton module is required in the main thread and also in modules that run in a web worker, the singleton module will get loaded a second time in the web worker (and so it isn't really a singleton). One copy is in the main thread, the other in the web worker. If your singleton stores variables, you'll have two copies.

    It all makes sense since the worker and main thread have separate address spaces (perhaps this is why I got a downvote?). I'm posting the answer here because someone might run into the same problem as there is no warning in requirejs.

    The solution (in my case) was not to mix modules between the main and web worker thread. This can be a big design constraint that isn't necessarily a problem in environments such as Java or C#.

    0 讨论(0)
  • 2020-12-05 00:28

    No, I cannot think of a reason against using singletons with require.js.

    Your module definition should export the singleton. The way you do it is fine, since it's a singleton you might be also able to avoid the new. I use something like

    define(function (require) {
        var singleton = function () {
            return {
                ...
            };
        };
        return singleton();
    });
    

    The first require to the module will load and export it. Some other module requiring your singleton will just reuse the already exported one.

    0 讨论(0)
提交回复
热议问题