// I need to

ModernizeUpgrade without breaking it RescueFix what someone else started Build NewTurn an idea into a product Reach More PeopleGet found, get used, include everyone

// Company

Case StudiesExpertiseAbout + CareersResourcesContact Book a call →

Fun with CoffeeScript and Backbone.js : Part 2

Part 2 of a CoffeeScript and Backbone.js morse code simulator: the view classes that animate a telegraph line and update the UI as characters decode.

Ryan Brubaker Jun 7, 20122 min read

From the Art+Logic archive · written in 2012. The tools may have moved on; the thinking still holds.

In this post I’ll discuss the code that handles updating the UI.

See the rest of this series.

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.

Communication Line View

class DecoderView extends Backbone.View
   initialize: ->
      @model.bind('parsedCharacter', @render)

   render: (token) =>
      messageBox = $('#messageBox')
      messageBox.val(messageBox.val() + token)

The CommunicationLineView class is a Backbone.js view class that handles the animation of signals sent across the communication line. In Part 1, I mentioned that the model representing the communication line fires a hasNewData event each time the tokens progress one step through the line. As you can see above, this view is bound to that event and rerenders itself every time it receives the event. The render method iterates over the current tokens and draws the appropriate token shape for each line position.

Decoder Model

class MorseDecoder extends Backbone.Model

   initializeKey: =>
      """
      Omitting code that initializes the morse code key 
      dictionary.
      """

   initialize: =>
      @inputTokens = []
      @numEmptyTokensInARow = 0
      @initializeKey()

   processToken: (token) =>
      if token == ''
         @parseTokens() if 
          ++@numEmptyTokensInARow >= 10
      else if token == kWordStopToken
         @parseTokens() if @inputTokens.length > 0
         @trigger('parsedCharacter', ' ')
      else
         @inputTokens.push(token)
         @numEmptyTokensInARow = 0

   parseTokens: =>
      if @inputTokens.length > 0
         token = @key[@inputTokens.join('')]
         @trigger('parsedCharacter', token) if 
          token != undefined
      @numEmptyTokensInARow = 0
      @inputTokens.length = 0

The Decoder model is responsible for determining what characters the user has sent across the line. The processToken function is called each time the tokens on the communication line progress one step through the line. The decoder processes the current tokens sent by the user anytime it sees 10 or more empty tokens in a row or receives a word-break token. If the decoder parses a known morse code sequence it fires a parsedCharacter event letting the message field know it needs to rerender itself.

Decoder View

class CommunicationLineView extends Backbone.View
   initialize: ->
      @model.bind('hasNewData', @render)

   render: (tokens) =>
      context = document.getElementById(
       "communicationLineCanvas").getContext('2d')

      context.clearRect(0, 0, context.canvas.width, 29)
      tokenNum = 0
      for token in tokens
         do (token) ->
            if kDotToken == token
               context.beginPath()
               context.moveTo((50 * tokenNum) + 15, 15)

               context.arc((50 * tokenNum) + 15, 15, 10, 
                0, Math.PI*2, false)

               context.closePath()
               context.fill()
               context.stroke()
            else if kDashToken == token
               context.fillRect((50 * tokenNum) + 15, 
                15, 25, 10)
            else if kWordStopToken == token
               context.fillRect((50 * tokenNum) + 30, 
                5, 10, 20)
            tokenNum += 1

The Decoder view is a Backbone.js view class that represents a simple text box to display the characters the user has sent across the line. Anytime the Decoder model emits a parsedCharacter event, the Decoder view appends the parsed character to the end of its text box.

keep going

More to explore in Reach More People.

All Reach More People resources →
let's talk

Got a problem like this one?

Tell us what's stuck. A real person replies within one business day.

Talk to our team →

Talk to people who know software, not a sales script.

Your first call is with Aja, our VP of Sales. He'll help make sure you're solving the right problem. Here's what you'll cover together:

  1. What you're trying to accomplish

    The business goal first, then the technology.

  2. Possible approaches

    And the tradeoffs of each, in plain language.

  3. Risks you may not have considered

    Technical and business, before they cost you.

  4. Whether AI changes the math

    What's practical, and what's just hype for your project.

  5. Sensible next steps

    Even if the right next step is not us.

book-a-call.ics

Loading the scheduler…

Open the booking page →

Some problems are easier to explain in writing. Send us a few lines about what you're working on, and we'll reply within one business day. Helpful to include:

  1. What the software does, or should do
  2. What's stuck, or what's worrying you
  3. Any deadline or budget you have in mind
note.md

Loading the form…