Search code examples
javascriptsingletoninstancerequirejsamd

Share prototype instance through requirejs without singelton pattern?


I got a mediator object which handles sandboxes.

Each sandbox has to register at the mediator. Because I also use requirejs this is a little problem because I have no idea how I could share the instance and not the prototype:

mediator.js

define([], function() {
    var Mediator = function() {};
    Mediator.prototype.start = function() {};
    Mediator.prototype.stop = function() {};
    Mediator.prototype.register = function() {};
    Mediator.prototype.unregister = function() {};
    return Mediator;
});

sandbox_one.js

define(['mediator'], function(Mediator) {
    var mediator = new Mediator();
    mediator.register('sandboxOne', SandboxObject);
});

sandbox_two.js

define(['mediator'], function(Mediator) {
    var mediator = new Mediator();
    mediator.register('sandboxtwo', SandboxObject);
});

As you have mentioned with the current approach I register the sandboxes at two different mediators. One idea to solve this would be the use of a singleton pattern but this conflicts with the architecture and requirejs recommandations..

So what other ways would I have to let the sandboxes register all to the same instance of Mediator?


Solution

  • Since I can't post comments, I'm going to post an answer.

    ggozad explains how to do a singleton in RequireJS here: Is it a bad practice to use the requireJS module as a singleton?

    His code:

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