Return to Snippet

Revision: 52699
at October 30, 2011 12:15 by ultranaut


Initial Code
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title></title>
  <meta name="description" content="">
  <script>
    Mediator = function () {
      var debug = function (m) {
            console.info(m)
          },

          components = {},

          addComponent = function (name, component, replaceDuplicate) {
            if (name in components) {
              if (replaceDuplicate) {
                removeComponent(name);
              }
              else {
                throw new Error('Mediator name conflict: ' + name);
              }
            }
            components[name] = component;
          },

          broadcast = function (event, args, source) {
            var c, s,
                e = event || false,
                a = args || [];

            if (!e) { return; }

            for (c in components) {
              if (typeof components[c]["on" + e] == "function") {
                try {
                  s = source || components[c];
                  components[c]["on" + e].apply(s, a);
                }
                catch (err) {
                  debug(["Mediator error.", e, a, s, err].join(' '));
                }ac
              }
            }
          },
          removeComponent = function (name) {
            if (name in components) { delete components[name]; }
          },
          getComponent = function (name) { return components[name] || false; },
          contains = function (name) { return (name in components); };

      return {
        name: "Mediator",
        broadcast: broadcast,
        add: addComponent,
        rem: removeComponent,
        get: getComponent,
        has: contains
      };
    }();

    Mediator.add('TestObject', function () {
      var someNumber = 0,    // sample variable
          someString = 'another sample variable';

      return {
        onInitialize: function () {
                  console.debug(this)
          // this.name is automatically assigned by the Mediator
          console.log(this.name + " initialized.");
        },
        onFakeEvent: function () {
          someNumber++;
          console.log("Handled " + someNumber + " times!");
        },
        onSetString: function (str) {
          someString = str;
          console.log('Assigned ' + someString);
        }
      }
    }());

  </script>

</head>
<body>

  <script>
    Mediator.broadcast("Initialize"); // alerts "TestObject initialized"
    Mediator.broadcast('FakeEvent'); // alerts "Handled 1 times!" (I know, bad grammar)
    Mediator.broadcast('SetString', ['test string']); // alerts "Assigned test string"
    Mediator.broadcast('FakeEvent'); // alerts "Handled 2 times!"
    Mediator.broadcast('SessionStart'); // this call is safely ignored
    Mediator.broadcast('Translate', ['this is also safely ignored']);
  </script>

</body>
</html>

Initial URL
http://arguments.callee.info/2009/05/18/javascript-design-patterns--mediator/

Initial Description
Somewhat tweaked

Initial Title
Mediator pattern (HB Stone)

Initial Tags
design

Initial Language
JavaScript