RequireJS Singleton with Web Workers

时间:2015-03-23 13:40:12

标签: javascript jquery requirejs

我正在使用最新的RequireJS创建一个Javascript项目。我正在定义一个chessWorker模块:

var worker;

define("chessWorker", ["jquery", "messageListener"], function($, listener) {
    if (worker) {
        return worker;
    } else {
        $.ajax({
            url: "...",
            success: function(data) {
                worker = new Worker(window.URL.createObjectURL(new window.Blob([data])));

                worker.onmessage = listener

                worker.error = function(e) {
                    ...
                };

                return worker;
            }
        });
    }
});

这是不好的做法吗?如果是这样,我该如何定义呢?是否有关于如何定义单身人士的标准?

1 个答案:

答案 0 :(得分:2)

确实不建议将worker定义为全局,而应该使用闭包来代替:

define(function(){
    var instance = null;

    function MySingleton(){
        if(instance !== null){
            throw new Error("Cannot instantiate more than one MySingleton, use MySingleton.getInstance()");
        } 

        this.initialize();
    }
    MySingleton.prototype = {
        initialize: function(){
            // summary:
            //      Initializes the singleton.

            this.foo = 0;
            this.bar = 1;
        }
    };
    MySingleton.getInstance = function(){
        // summary:
        //      Gets an instance of the singleton. It is better to use 
        if(instance === null){
            instance = new MySingleton();
        }
        return instance;
    };

    return MySingleton.getInstance();
});

注意:另外,请确保您的ajax调用是同步的,或者当您需要chessWorker模块时,您将获得null作为回复。