registerComponents.js

define(['knockout'], function(ko) {
    /**
     * This will handle the knockout component registration
     * @module app/registerComponents
     * @requires knockout
     * 
     * @example <caption>Normal usage</caption>
     * var my_array_of_components = [{
     *     name: 'my-component',
     *     dir: 'my-component/my-component'
     * }];
     * //adds it to the registered knockout components
     * registerComponents(my_array_of_components);
     * @example <caption>Template only usage</caption>
     * var my_array_of_components = [ {
     *       name: 'about-page',
     *       dir: 'about-page/about.html',
     *       templateOnly: true
     * }];
     * //adds it to the registered knockout components
     * registerComponents(my_array_of_components);
     *
     * @param  {Array} components                   Array of objects containing the component name as and the template name
     * @param  {String} customComponentsDirectory If the location is not on app/components, provide a custom directory
     * @return {None}                         
     */
    function registerComponents(components, customComponentsDirectory) {
        var config = null;
        var componentsDirectory = customComponentsDirectory || 'components/';

        ko.utils.arrayForEach(components, function(component) {
            if (component.templateOnly) {
                // template only components config
                config = {
                    template: {
                        require: 'text!' + componentsDirectory + component.dir
                    }
                }
            } else {
                // AMD components
                config = {
                    require: componentsDirectory + component.dir
                }
            }
            ko.components.register(component.name, config);
        });
    }

    return registerComponents;
});