Injector

by Sam Fereday

JavaScript

var SiteModules = (function () {

    'use strict';

    var attachedModules = [];

    function findModule(str) {

        return attachedModules.find(function (item) {

            return item.name === str;

        });

    }

    function addModule(name, cns) {

        var exists = findModule(name),
            mod = {
                name: '',
                inst: null
            };

        if (exists)
            throw "Cannot add module of same name.";

        mod.inst = new cns();
        mod.name = name;

        attachedModules.push(mod);

    }

    return {

        add: function (name, cns) {
            addModule(name, cns);
        },

        get: function (str) {
            var mod = findModule(str);
            return mod.inst;
        }

    };

})();