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 () {

var moveBackward = function () {

var moveFirst = function () {

var moveLast = function () {

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) {

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

For all the code, see github.

Comments are closed.

My Pluralsight Courses

K.Scott Allen OdeToCode by K. Scott Allen
What JavaScript Developers Should Know About ECMAScript 2015
The Podcast!