javascript 将 requireJS 模块用作单例是一种不好的做法吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9733201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:39:12  来源:igfitidea点击:

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

javascriptrequirejs

提问by Karthik

I plan to use the following pattern to make use of the requireJS based module to act as a singleton. Please notice that classAreturns an instance of type 'classA', whereas the rest of the classes classB, classC, and mainreturn the type of the class from the module. All of these are classes based on the MooTools Class.

我计划使用以下模式来利用基于 requireJS 的模块作为单例。请注意,classA返回一个类型为“classA”的实例,而其余的类classB、classC 和 main返回模块中类的类型。所有这些都是基于 MooTools 类的类。

The idea is to use the classAas a globally available singleton, the methods are just fillers. Any thoughts if this is an acceptable pattern to use?

这个想法是使用classA作为全局可用的单例,方法只是填充物。如果这是一个可以接受的模式,你有什么想法吗?

Will this come back to bite me at a later stage? I haven't tried to run r.js on the project yet, so I am a bit worried, and look for some advise.

这会在以后的阶段回来咬我吗?我还没有尝试在项目上运行r.js,所以我有点担心,寻求一些建议。

    // classA.js
    define([], function() {
        var classA = new Class({

            initialize: function (regionId) {
                // perform some Initialization.
                this.data = null;
            },

            doSomething: function(param) {
                // some thing.
                this.data = param;
            }
        };

        return new classA();
    });

    // classB.js
    define(["classA"], function(classA) {
        var classB = new Class({

            initialize: function (regionId) {
                // perform some Initialization.
            },

            doSomethingElse: function() {
                // some thing.
                classA.doSomething("Go back to Work Now!");
            }
        };

        return classB;
    });


    // classC.js
    define(["classA"], function(classA) {
        var classB = new Class({

            initialize: function (regionId) {
                // perform some Initialization.
            },

            doSomethingElse: function() {
                // some thing.
                classA.doSomething("Time to Play!");
            }
        };

        return classC;
    });


    // main.js
    define(["classA", "classB", "classC"], function(classA, classB, classC) {
        var main = new Class({

            initialize: function (regionId) {
                // perform some Initialization.
                this.b = new classB();
                this.c = new classC();
            },

            doEverything: function() {
                // some thing.
                this.b.doSomethingElse();
                classA.doSomething("Nap Time!");
            }
        };

        return main;
    });

Thanks much in advance...

非常感谢提前...

采纳答案by ggozad

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

不,我想不出反对在 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

您的模块定义应该导出单例。你这样做的方式很好,因为它是一个单身人士,你也可以避免new. 我使用类似的东西

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

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

require模块的第一个将加载和导出它。其他一些需要单例的模块只会重用已经导出的模块。

回答by Fuhrmanator

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 workerbecause it was doing a lot of calculations and the page was not responsive.

我从这里接受的答案的模式开始,但是我的单页 JavaScript 应用程序变成了一个主线程和一个网络工作者,因为它正在做大量的计算并且页面没有响应。

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.

当我将一些模块移入 Web Worker 时,出现了奇怪的行为。我花了很多时间才弄明白,但我意识到我的一些 requirejs 模块(即单例)被加载了两次。

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.

我发现如果主线程和web worker 中运行的模块都需要单例模块,那么单例模块将在 web worker 中第二次加载(因此它不是真正的单例模块) )。一份在主线程中,另一份在网络工作者中。如果您的单例存储变量,您将有两个副本。

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.

这一切都是有道理的,因为工作线程和主线程具有单独的地址空间(也许这就是我投反对票的原因?)。我在这里发布答案是因为有人可能会遇到同样的问题,因为 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#.

解决方案(就我而言)不是在主线程和 Web 工作线程之间混合模块。这可能是一个很大的设计约束,在 Java 或 C# 等环境中不一定是问题。