Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

There are various approaches to develop Backbone applications using ES2015 - for a more in depth discussion see https://benmccormick.org/2015/07/06/backbone-and-es6-classes-revisited/. We have decided that the approach that best suits our needs at edX is to treat everything like a method.

Backbone evaluates all of its properties using Underscore's _,results function, which checks to see whether an object property is a function. If it is then _,result will evaluate is and return the result, allowing Backbone to accept properties as either objects or functions. Knowing this we can work around the constructor problem by making everything a method, including properties. We can actually go one better than this, and use the get keyword to make our methods serve as getters for a property. This means they will be accessible as properties, but defined as methods, retaining compatibility with any existing references if you’re converting existing code.


class TodoView extends Backbone.View {

    get tagName() { return 'li'}

    get template() { return _.template(todosTemplate)}

    get events() {
        return {
            'click .toggle':    'toggleCompleted',
            'dblclick label':   'edit',
            'click .destroy':   'clear',
            'keypress .edit':   'updateOnEnter',
            'keydown .edit':    'revertOnEscape',
            'blur .edit':       'close'
        }
    }

    initialize() {
        this.listenTo(this.model, 'change', this.render);
        this.listenTo(this.model, 'destroy', this.remove);
        this.listenTo(this.model, 'visible', this.toggleVisible);
    }

    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());
    }

    //... etc
};

export default TodoView;



This approach uses only standard class syntax. Getters and methods are highly idiomatic class structures, and work fine with Backbone right now. They also enforce the immutability of these properties, a design concern with the current Backbone property implementation.