Client Code Structure, Part 3: Organization

Now that our code is split into Models and Controllers it is much easier to read, maintain, and debug. I thought that I could take it one step further, however. Once again, I pulled from my old ActionScript standards and split each file into the following sections:

  • Model Files
    • Property Initialization
    • That’s all (You expected more?)
  • ViewModel Files
    • Injectables
    • Inheritance
    • Scope Initialization
    • UI Event Handlers (Handles events from the view)
    • Application Event Handlers (Handles events from $rootScope)
    • General helper functions
    • Code that runs when the view is created
  • Controller Files
    • Injectables
    • Application Event Handlers 
    • Result Handlers
    • Fault Handlers
    • General helper functions
    • Code that runs when the app loads

See the example below:

divisionModule.factory('DivisionController',
    [

        /**************************************
        ***
        *** Injectables
        ***
        **************************************/

        '$rootScope',
        'DivisionModel',
        'DivisionService',

        function ($rootScope, DivisionModel, DivisionService) {

            /*********************************
            ***
            *** Application Event Handlers
            ***
            *********************************/

            function divisionSelectedHandler(event, division) {
                DivisionModel.selectedDivision = division;
            }
            $rootScope.$on('divisionSelected', divisionSelectedHandler);

            /********************************
            ***
            *** Result Handlers
            ***
            ********************************/

            function getDivisionsResultHandler(result) {
                //Apply the result
                DivisionModel.divisions = result;

                $rootScope.$emit('divisionSelected', selectedDivision);
            }

            /********************************
            ***
            *** Fault Handlers
            ***
            ********************************/

            function getDivisionsFaultHandler(fault) {
                //Handle faults
            }

            /******************************
            ***
            *** Helper Methods
            ***
            ******************************/

            function getDivisions(){
                DivisionService.query(queryParams, getDivisionsResultHandler, getDivisionsFaultHandler);
            }

            /******************************
            ***
            *** Code that runs on startup
            ***
            ******************************/

            getDivisions();
        }
    ]
);

Now, if there is a problem in the application somewhere, not only do we know exactly which file to look at, we also know which section of the file to look at.

 Next -> Client File Structure