Just Enough JavaScript

just-enough-js-1

I got a last-minute opportunity to teach an introduction to game programing course for people with no programming experience. I decided to base it around an open source HTML5 framework*. When I started looking around for a crash course with which to build basic JavaScript programming skills, I found none that were appropriate. Hence, Just Enough Javascript was born.

I’m creating it as a just-in-time resource for the course. There a little bad-but-expedient practice in there, but it’s working quite well for the course so far. Each page is resource-complete in itself—meaning you can download just a single HTML document and later view it without a live Internet connection.

I would love to hear any feedback about it.

* I considered enchant.js, Phaser, and melonJS. There were pros and cons to each, but I ultimately went with enchant.js because I like it’s event-driven nature (better reflects how JS “should” work) and it has a smaller (and therefore less intimidating for beginners) API.

(Over)thinking JavaScript objects 3

tally-clicker

Defining objects inside self-invoked anonymous functions

In our previous episode, we saw a canonical way to create objects in JavaScript that suggested code reuse and facilitated automatic object initialization, but it didn’t let you implement private attributes nor did it go out of its way to keep from polluting the global namespace.

What follows is the simplest way I’ve seen that accomplishes all of the above. And boy is it a ride! We are going to create a self-invoking anonymous function and inside the function we will define the object and create a single point of connection to the window with a closure.

Here we go:

// == Begin definition ==============================
(function(window) {
  // -- Constructor ---------------------------------
  var Clicker3 = function() {

    // -- Private properties --
    var _numClicks = 0;

    // -- Private methods --
    // Methods defined in this scope and not on
    // 'this' are private'.
    var _update = function() {
      console.log("Clicker3 obj: " + _numClicks);
    };

    // -- Public methods --
    // Methods defined on 'this' are public, can
    // access private and public members.
    this.click = function () {
      _numClicks++;
      _update();
    };

    this.reset = function () {
      _numClicks = 0;
      _update();
    };

    this.getNumClicks = function () {
      return _numClicks;
    };

    // -- Initialize state --
    this.reset(); // reset is redundant here;
                  // for demo only.
    _update();
  }; // !Clicker3()

  // -- "Hyper-public" methods ----------------------
  // Methods defined on the prototype can only access
  // public members!
  Clicker3.prototype.showInfo = function() {
    alert("I am a Clicker3 object who is at " +
      this.getNumClicks() + " clicks.");
  };

  // -- Publish -------------------------------------
  // Expose Clicker3 (and only Clicker3) to the
  // global window (i.e., make it public).
  window.Clicker3 = Clicker3;

}(window));
// == End definition ================================

The self-invoking function creates a new scope in which everything is defined. Passing in window as a parameter allows easy access to global window from within that new scope. This setup lets you:

  • Prevent pollution of global namespace.
  • Expose what you want to the global window and keep the rest private.

So, now we  have something that:

  • Has, “Reuse me!” written all over it.
  • Allows for automatic object initialization.
  • Lets you fully encapsulate objects.*
  • Protects the global namespace.

But it’s not totally cool because none of the above are code-level constructs. In other words, it’s neither readable or writable. JavaScipt is/isn’t fun. :-\

Just as a reminder, I am not (yet) taking on the following:

  • Inheritance-like stuff
  • “Class” (i.e., static) members*
  • Polymorphism

*An issue of religious importance.

Foray into TDD/BDD

laboratory-glassware-13792643839YO

I am starting a new programming project and have decided to use TDD and BDD as much as possible. Even though I currently suck at it, I think I am a convert. The confluence of testing automation, test writing, and spec writing is irresistible.

I only need to concern myself with JavaScript at the moment, so for my tooling I’m using Testem for test automation, Mocha for the testing framework, and Chai for the assertion library. I will probably have to delve into Sinon.js as well for mocks and other stuff. Personally, I’d be happy to use the the older and integrated Jasmine framework instead of the mix-and-match Mocha+Chai+Sinon.JS trinity, but Jasmine seems to be getting bad press lately for being stalled and for having clumsy async teset handling.

A Nettuts+ video on Testem helped make setting up easy. You should note that Testem has a "framework": "mocha+chai" option that makes it unnecessary to download chai.js.

So far, my code-to-test-code ratio is about 1 to 1.5. I have no idea if that’s typical.

(Over)thinking JavaScript objects 2

tally-clicker

Objects with constructors and prototyped methods

In this installment, I am going to look at building a tally clicker using what seems to be the canonical form for building class-like entities in JavaScript. The idea is simple:

  • Use a constructor function to create a scope/context with the object’s properties.
  • Use the constructor function’s prototype property to attach methods.

Attaching methods to the constructor’s prototype allows a single method instance to be shared among all objects instantiated from the constructor function.

Here’s how we might do it:

// == Begin Clicker2 definition =====================
// -- Constructor -----------------------------------
var Clicker2 = function() {
  // properties:
  this._numClicks = 0;

  // initialize state:
  this._update();
};

// -- Methods ---------------------------------------
Clicker2.prototype.click = function() {
  this._numClicks++;
  this._update();
};

Clicker2.prototype.reset = function() {
  this._numClicks = 0;
  this._update();
};

Clicker2.prototype._update = function() {
  console.log("Clicker2 obj: " + this._numClicks);
};

Clicker2.prototype.showInfo = function() {
  alert("I am a Clicker2 object who is at " +
    this._numClicks + " clicks.");
};
// == End Clicker 2 definition ======================

The HTML might then have something like:

<button onclick="yourClicker.click();">Click</button>
<button onclick="yourClicker.reset();">Reset</button>
<button onclick="yourClicker.showInfo();">Info</button>
...
<script>
  // Wait for DOM to be ready and then instantiate a
  // Clicker2 object:
  document.addEventListener('DOMContentLoaded',
    function() {
      document.yourClicker = new Clicker2();
    });
</script>

Compared to the approach using object literals, this approach has the following advantages:

  • It allows for automatic object initialization.
  • The object abstraction has, “Reuse me!” written all over it.

However, it still has a couple issues:

  • It violates encapsulation because everything is still public.*
  • It still pollutes the global namespace.

In the next installment, we’ll look at a way to fix these remaining problems. Just as a reminder, I am not (yet) taking on the following:

  • Inheritance-like stuff
  • “Class” (i.e., static) members*
  • Polymorphism

*An issue of religious importance.

(Over)thinking JavaScript objects 1

tally-clicker

I’ve always found JavaScript’s approach(es) to OOP a little cumbersome. I’m not talking here about prototypal vs. class-based OOP. Rather, I’m talking about the readability, etc. of the actual code you have to write to build objects. I want to take a few blog entries to try to put the maze into some kind of cohesive perspective.

I like to use a tally clicker to explore objects in languages I am learning. A tally clicker is a real-world object with a minimal set of features that are easy to implement and that map to basic but salient OOP concepts.

Object literals

I’m going to start this exploration with plain-Jane object literals. This is one of the canonical ways and often the first way shown to implement objects in JavaScript. Here’s how I might implement a tally clicker with a JavaScript literal:

// == Create a tally clicker ========
var myClicker = {

    // pseudo-private property
    _numClicks: 0,         

    // pseudo-private method
    _update: function() {
        console.log("myClicker1: " + this._numClicks);
    },

    // public methods
    click: function() {
        this._numClicks++;
        this._update();
    },

    reset: function() {
        this._numClicks = 0;
        this._update();
    },

    showInfo: function() {
        alert('I am "myClicker" and am at ' +
            this._numClicks + ' clicks.');
    }
}; // == End tally clicker ========

I might then stick something like this into the HTML:

<button onclick="myClicker.click();">Click</button>
<button onclick="myClicker.reset();">Reset</button>
<button onclick="myClicker.showInfo();">Info</button>

The object literal approach is a seductively easy and pretty readable way to build an object—but it’s got issues. Namely:

  • There’s no automatic initialization apart from property values.
  • It violates encapsulation because everything is public.*
  • It pollutes the global namespace (sort of). As is, the name of the object is in the global namespace.
  • The object abstraction doesn’t scream, “Reuse me!” (This may be a cognitive style issue more than anything else.)

In the next couple installments, I’ll consider some alternative implementations specifically with regard to the above criteria. For the moment, I will not deal with:

  • Inheritance-like stuff
  • “Class” (i.e., static) members*
  • Polymorphism

*An issue of religious importance.

Mozilla Brick and Zepto.js

old-red-brick-wall

Raymond Camden wrote up an instructive example that shows how to use Mozilla’s Brick UI Components with vanilla Javascript. I decided to take that and modify it to use Zepto.js instead. I have no idea whether this is a good idea or not, but it’s done now so there’s no point in crying about it. Here it is:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <!--
    From http://www.raymondcamden.com/index.cfm/2013/8/23/Brick-by-Mozilla
    Adapted to use Zepto.js by MFK.
    -->
    <title>Brick Card Demo</title>
    <meta name="description" content="" />
    <meta name="viewport" content="width=device-width" />
    <link rel="stylesheet" href="css/brick-1.0beta8.css"/>
    <script src="js/brick-1.0beta8.js"></script>
    <script src="js/zepto.min.js"></script>
    <style>
      html, body{
        height: 100%;
      }
    </style>
  </head>
  <body>

  <x-layout>
    <x-appbar>
      <div>
        <a href="" id="homeLink" title="Home">=</a>
      </div>
      <header>Brick Card Demo</header>
    </x-appbar>

    <section>
      <x-deck id="mainDeck">

        <x-card>
          <ul>
            <li>
              <a href="1" class="deckLink">Page 1</a>
            </li>
            <li>
              <a href="2" class="deckLink">Page 2</a>
            </li>
            <li>
              <a href="3" class="deckLink">Page 3</a>
            </li>
          </ul>
        </x-card>

        <x-card>
          <h1>Page 1</h1>
        </x-card>

        <x-card>
          <h1>Page 2</h1>
        </x-card>

        <x-card>
          <h1>Page 3</h1>
        </x-card>

      </x-deck>
    </section>

    <footer>
      Based on code
      copyright &copy;  2013 Raymond Camden
    </footer>
  </x-layout>

  <script>
    $(function() {
      console.log('domCom loaded (zepto.js!)');

      var deck = $('#mainDeck')[0];

      $('#homeLink').click(function(e) {
        e.preventDefault();
        deck.shuffleTo(0);
      });

      $('.deckLink').click(function(e) {
        e.preventDefault();
        var target = e.currentTarget.href.split("/").pop();
        deck.shuffleTo(target);
      });
    });
  </script>
</body>
</html>

Goodbye NURBS. Hello Printy.

target-baskets

The photo above was snapped at my local Target store yesterday. It tells me two things:

  • The era of NURBSy design has ended.
  • We have entered the era of printy design.

NURBSy design is what I call the aesthetic that has dominated product design over last couple decades. As soon as CAD tool companies introduced NURBS into their modeling products, we started to see products using NURBS everywhere. Need a handle for a kitchen strainer? Make it interesting by NURBSing it. Need a headlight? Make it interesting by NURBSing it. Etc. The availability of NURBS modeling tools led to its widespread and almost indiscriminate adoption, not the other way around. While this might be understandable, it must also be recognized that this is a fairly arbitrary approach to form.

Now, 3D printing is all the rage, and those engaged in making 3D printed design artifacts seem to be gravitating toward a common “faceted/fractally/spiderwebby” aesthetic. The aesthetic is ostensibly driven by the current limitations of 3D printing technology: the raw materials used in making prints are expensive and not that strong. The limited vocabulary of solutions that is emerging is striking. It’s as though referencing something that references 3D printing is more important than finding a really good or original solution. Or not. The main point here is that there is an emerging 3D printing aesthetic that is very identifiable.

To me, what’s most interesting about the objects in the photo above—and what leads me to think that we are now in the era of printy design—is that they were (as far as I was able to tell) not 3D printed. The form is simply a reference to a new and hip technology. Some might say that it’s a sign of the times.

This “sign of the times” approach to form isn’t exactly new in design. One of the things you should get from Corbu’s Towards a New Architecture is that he was actually much more interested in building a home that evokes the machine than in “building a machine for living in.” In a graduate design seminar a lot of years ago, the insightful Charles Owen referred to this kind of thinking among Modernists as “functionalistic” design. Evoking (and not necessarily signifying) functionality was more important than being functional. The aesthetic is the message. We can see this *-istic approach to form in the mid-century streamlining trend in the USA as well. There’s no compelling reason for a toaster to be streamlined, but many were. Lather, rinse, repeat.

What makes NURBSy and printy design different from functionalistic and streamlinistic design is that they reflect developments in design technology rather than developments from another field. I don’t really know what the significance of this is. The cynic in me has me thinking about isolationism, tribalism, and narcissism; the optimist is mumbling something about design discipline maturity and confidence but is otherwise silent.

In any case, what I am sure of is that all of this underscores the need for more dialog about the meaning of form in design. There is some, but we need a lot more.