Tuesday, July 7, 2015

odd little idea for javascript constants

Sometimes "magic numbers" in code are kind of unavoidable, especially if you're using basic CSS and js, and need to tell the js about some values that are hardcoded in the CSS.

Traditionally in coding, constants are represented in ALL_CAPS. In my http://jpporchfest.org project, I decided to bundle my constants as follows:

var CONST = {
    SCHEDULE : {
        ROWHEIGHT : 40,
        HEADERHEIGHT : 20,
        PORCHWIDTH : 200,
        MINUTE2PIXELRATIO : 2,
        SPACER : 3
    },
    HOUSEICON :{
        HEIGHT: 26
    },
    POINTER:{
        HEIGHT:34
    }
    
};

So the width of the porch column in the schedule is CONST.SCHEDULE.PORCHWIDTH. The cool thing is that with autocomplete, it makes it easy to find exactly what name I gave to any other constant, plus I have some semantic grouping here.

No comments:

Post a Comment