1

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?

bodokaiser
  • 15,122
  • 22
  • 97
  • 140
  • 1
    Can you explain a bit more? If you use the same instance everywhere, then you will have a singleton anyway, no matter how you call it? – JohnB Sep 23 '12 at 08:50

2 Answers2

2

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();
});
Community
  • 1
  • 1
Jan Sommer
  • 3,698
  • 1
  • 21
  • 35
0

Actually, with RequireJS you are already receiving singletons, so if you call:

require(['mediator'], function(Mediator) {
  ....
});

Mediator will be always the same object. If it's a constructor function, by calling new Mediator() you'll always create a new instance, but you'll use the same function each time.

But you don't have to return a function:

define([], function() {
    return {
        start: function() {},
        stop: function() {},
        register: function() {},
        unregister: function() {}
    };
});

Now your Mediator will be an instance, not a function, and you can't use it as function. You're example would now look like:

require(['mediator'], function(Mediator) {
  Mediator.register('sandboxOne', SandboxObject);
});

Disclaimer: I'm using RequireJS version build-in in Dojo.

Danubian Sailor
  • 1
  • 38
  • 145
  • 223