Fun with CoffeeScript and Backbone.js : Part 1

CoffeeScript has been all the rage lately and I’ve been wanting to hop on board the bandwagon. I’ve also seen Backbone.js mentioned quite a bit and was even more intrigued after listening to this .NET Rocks podcast. I decided to convert some plain JavaScript code I had in a side project to use both CoffeeScript and Backbone.js and see how things went.

The project is a simplified morse code simulator that animates morse code being sent over a telegraph line. The complete source is available here and the running code can be seen here.

The class uses two timers to determine which “token” a user intends to send across the line. Using Backbone’s declarative style for event binding, I bind the mousedown event to a function that starts both timers. The mouseup event is bound to a function that pushes the appropriate token to the model based on how long the user held down the input button.

The CommunicationLine class is a Backbone model class that represents the tokens currently moving across the telegraph line. It also contains a queue that holds the input tokens generated by the user. The class also holds a reference to the object responsible for decoding the user input (more on that tomorrow).

Every 100 milliseconds, the communication line shifts its tokens over one spot. The token popped off the line is passed to the decoder. The model then checks the input queue to determine if a user-generated token is available to be pushed onto the line. If not, the model pushes a default token (an empty string). The model then triggers an event to indicate the communication line state has changed and that the object representing the communication line view needs to be re-rendered (more on that tomorrow).

Art+Logic has been designing and developing innovative custom software since 1991. We have built software for over 900 clients from a diverse set of industries including education, aerospace, music technology, consumer electronics, entertainment, financial services, and more. Coding the “impossible.”®