Backbone.js application in TypeScript with require.js

Submitted by Erik Wegner on
Aufmacherbild

The new GitHub repository contains a rebuild of the Backbone tutorial in TypeScript.

TypeScript adds classes, modules, scopes and types to JavaScript.

The library Backbone.js is especially useful for maintaining elements and views in the browser. It contains all parts to build single page apps.

There were a few challenges to handle:

  1. Backbone.js uses an extend method to provide an inheritance mechanism. The TypeScript compiler concurrently has its own extend function. The used definition file hides the Backbone function. Instead, the TypeScript class inheritance is heavily recommended. As a result, several constructors and initialize functions have been refactored. Registering the events is done in a slightly different way.
  2. Putting the parts (model, collection, view) into their own files and loading with require.js. Each TypeScript files results in a single JavaScript file. Modules are defined to reuse classes and functions from other files. The compiler can generate modules as CommonJS (node.js) or AMD (require.js). The source files contain import statements, the result automatically has the corresponding require call. This allows to a) keep the TypeScript files small and b) load files on demand.