Skip to content

Instantly share code, notes, and snippets.

@hwclass
Created July 2, 2015 09:15
Show Gist options
  • Save hwclass/bc60ae16e95f239363f5 to your computer and use it in GitHub Desktop.
Save hwclass/bc60ae16e95f239363f5 to your computer and use it in GitHub Desktop.
Design Patterns : Mediator Pattern
/**
* @fileoverview The boot file to start or stop the modules
* @author hwclass
*/
/**
* boot.js
* This file is used to initialize the modules
*/
'use strict';
//-----------------------------------------------------------
// Public
//-----------------------------------------------------------
Mediator.module.start('testModule');
//Mediator.module.stop('testModule');
/**
* @fileoverview The mediator object file
* @author hwclass
*/
/**
* Mediator.js
* This object is used to fetch needed configuration parameters
*/
'use strict';
//-----------------------------------------------------------
// Public
//-----------------------------------------------------------
/**
* Mediator object
* @noparam
*/
var Mediator = (function () {
/** @type {Array} */
var MODULES = MODULES || [];
/**
* Module object
* @param {String} name
* @param {Function} context
*/
var Module = function (name, context) {
this.name = name;
this.context = context;
};
/**
* attachModule method
* @param {Module} module
*/
var attachModule = function (module) {
MODULES.push(new Module(module.name, module.context));
};
/**
* startModule method
* @param {String} moduleName
*/
var startModule = function (moduleName) {
for (var counter = 0, len = MODULES.length; counter < len; counter++) {
if (MODULES[counter]['name'] === moduleName) {
MODULES[counter]['context']();
}
}
};
/**
* stopModule method
* @param {String} moduleName
*/
var stopModule = function (moduleName) {
for (var counter = 0, len = MODULES.length; counter < len; counter++) {
if (MODULES[counter]['name'] === moduleName) {
MODULES[counter] = null;
}
}
};
return {
module : {
attach : attachModule,
start : startModule,
stop : stopModule
}
}
})();
<!--
testView.html
The base html file to register the module into mediator's collection.
-->
<script type="text/javascript">
Mediator.module.attach({name : 'testModule', context : function () {
console.log('testModule initialized');
}});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment