r/jquery • • Nov 03 '15

Unsuck my javascript

https://github.com/sleepyhead2gist/fullcalendar_bootstrap_tasklogger

This code uses FullCalendar and Bootstrap modal to log events into the calendar.

I am mostly a Photoshop/CSS person and would like to get better at JS.

This frankenstein-ish code that was cobbled together needs improvement and any input would be appreciated!

Some points that needs improvement in /test/source/javascript/custom.js

  • I've read that polluting global scope is bad. Some of my functions are in global scope Ex. validationCheck() . How can I include this function within the calendar scope?

  • My code has parts that are duplicated in 2 different functions. How can I consolidate duplicated parts so it can be used in different methods inside the calendar object?

I'm sure there are many others areas to improve so feel free to rip me a new one :)

0 Upvotes

3 comments sorted by

2

u/[deleted] Nov 04 '15 edited Nov 04 '15

Break everything apart, it is SUPER rigid and difficult to read by defining all of your calendar options and vars inside the invocation. The only thing that needs to occur at docready is the calendar invocation, not calculating all of your values.

You should have zero variable definitions or method calls in there ( $( elem ) counts as a method call too )

You have inconsistent tab/space indentation.

You call functions synchronously before they are defined.

1

u/noodlylegs Nov 04 '15

Thanks - those are all valid points. What's the best way to get variable definitions / method calls out of invocation and still get those values into the calendar?

1

u/[deleted] Nov 05 '15 edited Nov 06 '15

I'd recommend also to abstract and generalize as many functions as you can and split them out of your calendar function into a set of utility functions. No function should do both getting and setting of data.

Some of your functions were a little too convoluted for me to want to spend time digging into, but there are several candidates for utils - validation, binding, table generation, and I am certain there are more. The date parse function I created could also be a util function as it can apply beyond the scope of the application.

If you are running node, you can split it up even more with browserify by spreading discrete components across multiple files and requiring them. You can split it up as event.js, calendar.js, utils.js, settings.js/json, data.js/json and piece them together and initiate them in a main.js which would be compiled and included

Sorry I rearranged some things on my phone so formatting may be off.

var settings = {
        forceEventDuration: true,
        allDayDefault     : false,
        displayEventEnd   : true,
        editable          : true,
        events            : null
    };
  var events   = [
                {
                    id: today + '02E' + Math.random(),
                    client_name  : 'Susan McCormick',
                    start  : today + '02T18:00:00',
                    end    : today + '02T21:00:00',
                    hours: 3.00,
                    rate: 14.75,
                    total: 44.25,
                    work_subject: 'Image retouching',
                    work_description: 'Adjust brightness and contrast for wedding pictures'
                },
                {
                    id: today + '07E' + Math.random(),
                    client_name  : 'Roy Nelson',
                    start  : today + '07T11:00:00',
                    end    : today + '07T21:30:00',
                    hours: 10.50,
                    rate: 22.00,
                    total: 297,
                    work_subject: 'Change theme color',
                    work_description: 'Change the main theme color from blue to red'                    
                },
                {
                    id: today + '19E' + Math.random(),
                    client_name  : 'Ben White',
                    start  : today + '19T09:00:00',
                    end    : today + '19T18:30:00',
                    hours: 9.50,
                    rate: 32.00,
                    total: 304,
                    work_subject: 'Javascript refactoring',
                    work_description: 'Refactor duplicate codes into a function'                    
                }                             
            ];


var Event = function ( start, end, rate, client, subject, desc ) {
    var start       = this.parseDate( start );
    var end         = this.parseDate( end );

    this.id         = start.ymd + 'E' + Math.random( );
    this.clientName = client;
    this.start      = start.iso;
    this.end        = end.iso;
    this.hours      = ( end.hours + end.minutes / 60 ) - ( start.hours + start.minutes / 60 );
    this.rate       = rate;
    this.total      = this.hours * rate;
    this.subject    = subject ? subject : '';
    this.desc       = desc ? desc : '';
};

Event.prototype.parseDate = function ( date ) {
    var date = new Date( Date.parse( date ) );

    var dateObj = {
        object : date,
        year   : date.getUTCFullYear( ),
        month  : date.getUTCMonth( ) + 1,
        date   : date.getUTCDate( ),
        hours  : date.getUTCHours( ),
        minutes: date.getUTCMinutes( ),
        seconds: date.getUTCSeconds( )
    };

    dateObj.ymd = dateObj.year + '-' + ( '0' + dateObj.month ).slice( -2 ) + '-' + ( '0' + dateObj.date ).slice( -2 );
    dateObj.time = ( '0' + dateObj.hours ).slice( -2 ) + ':' + ( '0' + dateObj.minutes ).slice( -2 ) + ':' + ( '0' + dateObj.seconds ).slice( -2 );
    dateObj.iso = dateObj.iso + 'T' + dateObj.time;


    return dateObj;
};

var Calendar = function ( settings ) {
    this.settings: settings;
};

Calendar.prototype.init = function ( selector, eventSource ) {
    var _this = this;
    /* Get data */
    var eventSource = JSON.parse( eventSource );
    var events = [];

    for ( var i = 0; i < eventSource.length; i++ ) {
        events[ i ] = new Event( eventSource[ i ].start, /*....*/ eventSource[ i ].work_description );
    };

    _this.events = events;
    /* Set up, binding, etc */
    _this.display( );

    $( selector ).fullCalendar( this.settings );
};

Calendar.prototype.dayClick = function ( date, jsEvent, view ) {
    /*...*/
};

Calendar.prototype.eventClick = function( event, jsEvent, element ) {
    /*...*/
};

Calendar.prototype.eventDrop = function( event, delta, revertFunc, jsEvent ) {
    /*...*/
};

Calendar.prototype.eventRender = function( event, element, view ) {
    /*...*/
};

Calendar.prototype.validationCheck = function ( ) {
    /* Validation stuff */
};

Calendar.prototype.display = function ( ) {
    /* Stuff related to display and rendering */
};

var calendar = new Calendar( settings );

$( document ).ready(
    function( ) {
        calendar.init( '#calendar', events );
    }
);