Dynamically retrofitting legacy JavaScript classes as Backbone models

The code.

When I originally wrote my Jeopardy Scorekeeper single-page app with just JavaScript and jQuery, I wrote what are essentially model classes that implement the game and player logic (keeping score, tracking remaining clues, rotating players, etc.) and that have no user interface functionality, other than the abstract concept of the Jeopardy UI (the board, etc.). I decided to try refactoring the Jeopardy Scorekeeper with Backbone, but I also wanted to:

  • Be able to keep showing the original, non-Backbone version.
  • Be able to make changes to the core logic as time goes on without duplicating code in the Backbone / non-Backbone versions.
  • Avoid changing the original code any more than necessary.

So, I did an experiment in writing code to dynamically retrofit my classes to serve as Backbone.Model classes.

The gist of it is that it copies the methods and properties (which will become the Backbone model attributes) from the legacy class to a new object which is passed to Backbone.Model.extend(). For the attribute properties, getters / setters (in this case, the ES5 variety) are created, which proxy to Backbone.Model get() / set(). That allows standard property access in the original class to continue to function and to refer to the same attribute data as the Backbone.Model get() / set() calls used in the Backbone code. E.g.:

// Original class

var clue_value = this.current_clue;


this.current_clue = 0;

// Backbone code

this.set( 'current_clue', 400 );


this.get( 'current_clue' ) === 0;

I’d say this experiment has been moderately successful.

Leave a Reply

Your email address will not be published. Required fields are marked *

Note: Comments are moderated. Spam comments will never be published.

Is this comment spam?