Rewriting A WebApp With ECMAScript 6

Introduction

Today it’s possible for us to author in ES6 and transpile our sources down to ES5 at build-time, regardless of whether we’re using Grunt, Gulp or Broccoli. With projects like Ember and Angular looking to ES6 as part of their roadmaps too (Ember App Kit already supports ES6 modules!), now is a great time to learn how ES6 can be used in practice.

In this guide, we’ll re-write the well known TodoMVC application (implemented with Backbone.js) using ECMAScript 6 language semantics. The implementation is made possible using Google’s Traceur compiler and ES6-Module-Loader.

If you haven’t come across these tools before, Traceur is a JavaScript.next-to-JavaScript-of-today compiler that allows you to use features from the future today and the ES6 Module Loader dynamically loads ES6 modules in Node.js and current browsers. If you’re wondering whether Traceur is ready for production-level apps, Erik Arvidsson recently answered this on their mailing list.

Features covered

Features we will be using in this walkthrough include but are not limited to:

Source & Demos

You can run the completed app, view a Docco version of the tutorial (app.html and todo-app.html) watch the project repository or look at the original ES5 implementation.

The application was rewritten in ES6 by Addy Osmani, Pascal Hartig, Sindre Sorhus, Stephen Sawchuk, Rick Waldron, Domenic Denicola and Guy Bedford.

Begin your ES6 adventure here

Our application is composed of primarily three files:

  • index.html — containing our templates and initial module loading.
  • app.js — our main entry point for the app
  • todo-app.js — our Todos module

It is also composed of stylesheets and of course our Backbone, Traceur and ES6 Module Loader dependencies, but we’ll focus on the ES6 portions of the application in this guide.

Index (index.html)

We first dynamically load our main application — a script located at js/app.js.

System.import is an asynchronous loader for loading such modules and doesn’t require us to include the extension to our script. This is automatically inferred:

The two script files we’ll be using for this application are js/app.js and js/todo-app.js. They are ES6 modules.

ES6 modules allow us to define isolated blocks of reusable code without having to wrap it into an object or closure. Only those functions and variables we explicitly export are available to other consumers and we can just as easily import functionality from other modules. It’s possible to rename exported values, define modules that are inline and even declare defaults for import/export.

Application entry-point (app.js)

Imports

We import the classes we defined in the TodoApp module using the import keyword.

import {AppView, Filters} from './todo-app';

Document ready

Arrow Functions (Statements)

We then load the application once the DOM is ready, using jQuery.ready () => { … } which you’ll see below is the statement form of the arrow function syntax. Practically speaking, it is lightweight sugar for function () { … }.bind(this).

Apart from containing statements instead of an automatically-returned expression, it has the same properties as the expression-form arrow functions we look at below:

$(() => { // Finally, we kick things off by creating the App. new AppView(); new Filters(); Backbone.history.start(); });

TodoApp Module (todo-app.js)

Destructuring Assignments

Constant (const) declarations are block scoped, and cannot be re-declared or have their value reassigned once the binding is initialized.Backbone’s core component definitions don’t need to be modified, so we can combine constants and an ES6 pattern called destructuring assignment to create shorter aliases for Models, Views and other components.

This avoids the need to use the more verbose Backbone.* forms we’re accustomed to. Destructuring of array and object data uses a syntax that mirrors the construction of array and object literals.

const is currently disabled in Traceur due to https://github.com/google/traceur-compiler/issues/595 but it would otherwise be written as:

const { Model, View, Collection, Router, LocalStorage } = Backbone;

We’ll use var here for now as we require a functional implementation:

var { Model, View, Collection, Router, LocalStorage } = Backbone; // Note, if Backbone was written with ES6 you // would use an import for this. var ENTER_KEY = 13; // const var TodoFilter = ''; // let

Todo Model class

Classes

In JavaScript, we’ve relied on prototypal inheritance anytime we’ve needed a class-like system. This has led to overly verbose code using custom types. ES6 changes that by removing the ugly multi-step inheritance patterns we’re used to and introducing a minimal class syntax that makes defining classes a lot more terse.

ES6 classes desugar to prototypal inheritance behind the scenes and the only real change is that there’s less typing required for us. Classes are compact and we can use an ‘extends’ keyword to implement a new sub-class from a base-class. Below, we do this to define a Todo class which extends Backbone’s Model component.

class Todo extends Model { // Note the omission of the 'function' keyword // Method declaractions inside ES6 classes don't // use it // Define some default attributes for the todo. defaults() { return { title: '', completed: false }; } // Toggle the `completed` state of this todo item. toggle() { this.save({ completed: !this.get('completed') }); } }

TodoList Collection class

We define a new class TodoList extending Backbone’s `Collection. The collection of todos is backed by localStorage instead of a remote server.

class TodoList extends Collection {

Constructors and Super Constructors

Specifying a constructor lets us define the class constructor. Use of the super keyword in your constructor lets you call the constructor of a parent class so that it can inherit all of its properties.

constructor(options) { super(options); // Hold a reference to this collection's model. this.model = Todo; // Save all of the todo items under the 'todos' namespace. this.localStorage = new LocalStorage('todos-traceur-backbone'); }

Arrow Functions (Expressions)

The arrow (=>) is shorthand syntax for an anonymous function. It doesn’t require the function keyword and the parens are optional when there’s a single parameter being used. The value of this is bound to its containing scope, and when an expression follows the arrow — like in this case — the arrow function automatically returns that expression’s value, so you don’t need return.

Arrow functions are more lightweight than normal functions, reflecting how they’re expected to be used — they don’t have a prototype and can’t act as constructors. Because of how they inherit this from the containing scope, the meaning of this inside of them can’t be changed with call or apply.

To recap, when using =>:

  • The function keyword isn’t required.
  • Parentheses are optional with a single parameter.
  • return is unnecessary with a single expression.
  • Arrow Functions are lightweight — no prototypes or constructors

We use an arrow function below for our method that sets a Todo item as being completed:

completed() { return this.filter(todo => todo.get('completed')); }

Next, we look at filtering down the list to only todo items that are still not finished.

remaining() { // The ES6 spread operator reduces runtime boilerplate  // code by allowing an expression to be expanded where  // multiple arguments or elements are normally expected.  // It can appear in function calls or array literals. // The three dot syntax below is to indicate a variable // number of arguments and helps us avoid hacky use of // `apply` for spreading. // Compare the old way... return this.without.apply(this, this.completed()); // ...with the new, significantly shorter way... return this.without(...this.completed()); // This doesn't require repeating the object on which  // the method is called - (`this` in our case). }

We keep the Todos in sequential order, despite being saved by unordered GUID in the database. This generates the next order number for new items.

nextOrder() { if (!this.length) { return 1; } return this.last().get('order') + 1; }

Todos are sorted by their original insertion order using a simple comparator.

comparator(todo) { return todo.get('order'); } }

Create our collection of Todos.

var Todos = new TodoList();

Todo Item View class

We create a TodoView class by extending Backbone’s View as follows:

class TodoView extends View { constructor(options) { super(options); // The DOM element for a todo item // is a list tag. this.tagName = 'li';

Next we setup a cached instance of our template and DOM listener events for individual items:

// Cache the template function for a single item. this.template = _.template($('#item-template').html()); this.input = ''; // Define the DOM events specific to an item. this.events = { 'click .toggle': 'toggleCompleted', 'dblclick label': 'edit', 'click .destroy': 'clear', 'keypress .edit': 'updateOnEnter', 'blur .edit': 'close' }; this.listenTo(this.model, 'change', this.render); this.listenTo(this.model, 'destroy', this.remove); this.listenTo(this.model, 'visible', this.toggleVisible); }

Re-render the contents of the todo item.

render() { this.$el.html(this.template(this.model.toJSON())); this.$el.toggleClass('completed', this.model.get('completed')); this.toggleVisible(); this.input = this.$('.edit'); return this; } toggleVisible() { this.$el.toggleClass('hidden', this.isHidden); }

Accessor Properties

isHidden() is a get accessor property, but commonly referred to as a ‘getter’. Although technically part of ECMAScript 5.1, getters and setters allow us to write and read properties that lazily compute their values. Properties can process values assigned in a post-process step, validating and transforming during assignment.

In general, this means using set and get to bind a property of an object to a function which is invoked when the property is being set and looked up. Read more on accessor properties, or ‘getters and setters’.

get isHidden() { var isCompleted = this.model.get('completed'); return (hidden cases only (!isCompleted && TodoFilter === 'completed') || (isCompleted && TodoFilter === 'active') ); }

Toggle the ‘completed’ state of the model.

toggleCompleted() { this.model.toggle(); }

Switch this view into ‘editing’ mode, displaying the input field.

edit() { var value = this.input.val(); this.$el.addClass('editing'); this.input.val(value).focus(); }

Close the ‘editing’ mode, saving changes to the todo.

close() { var title = this.input.val(); if (title) { // Note that here we use the new  // object literal property value  // shorthand this.model.save({ title }); } else { this.clear(); } this.$el.removeClass('editing'); }

If you hit enter, we’re through editing the item.

updateOnEnter(e) { if (e.which === ENTER_KEY) { this.close(); } }

Remove the item and destroy the model.

clear() { this.model.destroy(); } }

The Application class

Our overall AppView is the top-level piece of UI.

export class AppView extends View { constructor() {

Instead of generating a new element, bind to the existing skeleton of the App already present in the HTML.

this.setElement($('#todoapp'), true); this.statsTemplate = _.template($('#stats-template').html()),

Delegate events for creating new items and clearing completed ones.

this.events = { 'keypress #new-todo': 'createOnEnter', 'click #clear-completed': 'clearCompleted', 'click #toggle-all': 'toggleAllComplete' };

At initialization, we bind to the relevant events on the Todos collection, when items are added or changed. Kick things off by loading any preexisting todos that might be saved in localStorage.

this.allCheckbox = this.$('#toggle-all')[0]; this.$input = this.$('#new-todo'); this.$footer = this.$('#footer'); this.$main = this.$('#main'); this.listenTo(Todos, 'add', this.addOne); this.listenTo(Todos, 'reset', this.addAll); this.listenTo(Todos, 'change:completed', this.filterOne); this.listenTo(Todos, 'filter', this.filterAll); this.listenTo(Todos, 'all', this.render); Todos.fetch(); super(); }

Re-rendering the App just means refreshing the statistics — the rest of the app doesn’t change.

render() { var completed = Todos.completed().length; var remaining = Todos.remaining().length; if (Todos.length) { this.$main.show(); this.$footer.show(); this.$footer.html( this.statsTemplate({ completed, remaining }) ); this.$('#filters li a') .removeClass('selected') .filter(`[href="#/${TodoFilter || ''}"]`) .addClass('selected'); } else { this.$main.hide(); this.$footer.hide(); } this.allCheckbox.checked = !remaining; }

Add a single todo item to the list by creating a view for it, then appending its element to the <ul>.

addOne(model) { var view = new TodoView({ model }); $('#todo-list').append(view.render().el); }

Add all items in the Todos collection at once.

addAll() { this.$('#todo-list').html(''); Todos.each(this.addOne, this); } filterOne(todo) { todo.trigger('visible'); } filterAll() { Todos.each(this.filterOne, this); }

Generate the attributes for a new Todo item.

newAttributes() { return { title: this.$input.val().trim(), order: Todos.nextOrder(), completed: false }; }

If you hit enter in the main input field, create a new Todo model, persisting it to localStorage.

createOnEnter(e) { if (e.which !== ENTER_KEY || !this.$input.val().trim()) { return; } Todos.create(this.newAttributes()); this.$input.val(''); }

Clear all completed todo items and destroy their models.

clearCompleted() { _.invoke(Todos.completed(), 'destroy'); } toggleAllComplete() { var completed = this.allCheckbox.checked; Todos.each(todo => todo.save({ completed })); } }

The Filters Router class

export class Filters extends Router { constructor() { this.routes = { '*filter': 'filter' } this._bindRoutes(); }

Default Parameters

param in the filter() function is using ES6’s support for default parameter values. Many languages support the notion of a default argument for functional parameters, but JavaScript hasn’t until now.

Default parameters avoid the need to specify your own defaults within the body of a function. We’ve worked around this by performing logical OR (||) checks against argument values to default if they’re empty/null/undefined or of the incorrect type. Native default parameter values provide a much cleaner solution to this problem. Notably they are only triggered by undefined, and not by any falsy value.

Compare the old way…

function hello(firstName, lastName) { firstName = firstName || 'Joe'; lastName = lastName || 'Schmo'; return 'Hello, ' + firstName + ' ' + lastName; }

…to the new way, where we can also drop in Template String..

function hello(firstName = 'Joe', lastName = 'Schmo') { return `Hello, ${firstName} ${lastName}`; }

which we implement as follows:

filter(param = '') { // Set the current filter to be used. TodoFilter = param; // Trigger a collection filter event,  // causing hiding/unhiding of Todo view  // items. Todos.trigger('filter'); } }

And that’s it. Don’t forget you can check out the source for the application over on the project repository.

Web Components

Although we haven’t seen a huge amount of research into how ES6 modules will play with Web Components, Guy Bedford has been exploring this (via Polymer) and we’re looking forward to more examples of interop in the wild.

Tracking ECMAScript 6 Support

ECMAScript 6 is being progressively implemented by browser vendors over time and as such there is no ‘fixed’ date on it being available everywhere.

Whilst specs and implementations continue to finalize and ship, you may find the below resources helpful in keeping track of where we are with browser and environment support:

  • Feature comparison matrix of ECMAScript implementations (V8, JSC, JScript etc) by Thomas Lahn
  • Harmony features available in Node can be listed with node —v8-options | grep harmony
  • ECMAScript 6 compatibility table by Kangax
  • Google’s V8: Harmony features with corresponding open bugs in on the tracker (i.e what ES6 features Chrome and Opera will support, either by default or behind the about:flags > ‘Enable Experimental JavaScript’ flag).
  • ECMAScript 6 support in Firefox (MDN). There is also a meta-bug on Buzilla you can check-out that’s slightly more in the trenches (HT @domenic). In addition, Rick Waldron suggests subscribing for component notifications from bugzilla and then creating a filter, however this might be a little high-volume.
  • IE Dev Center on supported ES6 features (hunting down a better list for IE11+)
  • ECMAScript 6 official draft specification (and the unofficial HTML version of the draft)

We recommended that you follow @esdiscuss for a summary of what is happening on the es-discuss mailing list for links to the latest discussions.

Sindre Sorhus also maintains a list of real-world usage of ECMAScript 6 features in today’s libraries and frameworks that may be of interest.

ES6 Tools

If you’re interested in doing the deep-dive into ES6 today, the community has an evolving list of tools that can help with your workflow over at https://github.com/addyosmani/es6-tools.

We’ve also recently been playing with http://es6fiddle.net, which is awesome for experimenting with ES6 with zero-setup. Try it out!.

Wrapping up

In closing, we hope you found this brief walkthrough helpful. We’re pretty excited about seeing ES6 used to author more projects and invite you to share your own ES6 authoring experiences with us on Twitter.

With lots of ❤z,

Addy, Sindre, Pascal and Stephen.

With special thanks to Rick Waldron and Domenic Denicola for their reviews.


Originally published at blog.tastejs.com on February 24, 2014.