Primitive JavaScript (BYOSP Part 7)

Tuesday, February 28, 2012

When starting into the animations I decided it was time to refactor. One problem was the little "updateState" calls floating around inside conditional logic – always a bad sign. A second problem was the sheer number of strings and CSS selectors in the code.

I've become more sensitive to primitive obsession in JavaScript. Some code I see is nothing but strings and numbers. I think the obsession hurts readability and maintainability.

The selectors scattered in the slide presenter code do one of three things: get all slides, get the next slide, and get the previous slide. It would be nice to hide all of these behind tiny function abstractions.

var slides = function () {
    return $("section");
};

var nextSlide = function () {
    return $("section.current").next("section");
};

var previousSlide = function () {
    return $("section.current").prev("section");
};

Those functions make the logic for moving around much easier to read.

var moveForward = function () {
    setCurrentSlide(nextSlide());
};

var moveBackward = function () {
    setCurrentSlide(previousSlide());
};

var moveFirst = function () {
    setCurrentSlide(slides().first());
};

var moveLast = function () {
    setCurrentSlide(slides().last());
};

As a bonus, all of the book keeping logic for setting the current slide moves into a single location.

var setCurrentSlide = function (slide) {
    if (slide.length > 0) {
        slides().removeClass("current");
        slide.addClass("current");
        updateHistory(slide);
    }
};

Having a central location to set the currently selected slides is important for the upcoming animation logic.

For all the code, see github.


Comments
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!