Swizec Teller - a geek with a hatswizec.com

    Backbone with ES6

    Dan avatarDan@dan_abramov
    I don’t know about you but I’m amazed by how many solutions there are for writing maintainable apps these days. Remember 7 years ago.

    Ah yes, Dan Abramov. How right he is! Building maintainable apps for the browser has never been easier or more fun. Life is great.

    That is, if you’re Dan Abramov and you spend your days building the future of web technology. I don’t know how he built that life, but I’m impressed.

    Swizec Teller published ServerlessHandbook.dev avatarSwizec Teller published ServerlessHandbook.dev@Swizec
    @dan_abramov and here I am in the real world, looking at all these solutions, and thinking "Man, 7 years from now is gonna be nice"

    The real world is not like that. For us, building businesses is the important part, not building technologies. We’re building technology in the service of business innovation.

    Unless it’s a weekend hack project, or a fun toy for the soul, we don’t get to throw everything away and re-engineer from scratch every 6 months when new libraries become available. We don’t even get to do it every year.

    If you can’t make a business case for it, it doesn’t happen.

    But we do what we can. We evolve rather than rewrite. Baby step after baby step, our tech stacks become better and more fun to use. They are driven by business needs rather than creature comforts.

    We’re highly paid professionals, after all. You wouldn’t expect a race car driver to only drive cars with air conditioning, would you? (Hint: There’s no such thing as AC in race cars. It’s too heavy.)

    All that to say that if you’re still using Backbone, you too can use ES6 classes! ?

    /giphy partyhard

    Here’s how you do it

    Let’s take a basic Backbone View. It renders as a div element, uses a template, and responds to user events. A click counter, for example.

    In traditional Backbone, it would look like this:

    var Counter = Backbone.View.extend({
    tagName: "div",
    model: new Backbone.Model(),
    template: Handlebars.compile("{count} <button>++</button>"),
    events: {
    "click button": "buttonClick",
    },
    initialize: function () {
    this.model.set({ count: 0 });
    this.listenTo(this.model, "change", this.render);
    },
    render: function () {
    this.$el.html(this.template(this.model.attributes));
    },
    buttonClick: function () {
    this.model.set({ count: this.model.get("count") + 1 });
    },
    });

    Cool, huh? Don’t worry if you don’t know what any of that means; you’re just not the target audience for this article. :)

    The quick explanation is that we create a View backed by an anonymous Model. The model holds a count value, we listen for click events on the button element, and we increase the count when they happen. And we listen for change events on the model to decide when to re-render.

    If this sounds similar to React, that’s because it is. Backbone was, and still is, very close to React in its core ideas. React just happens to implement them better and make it easier to better architect your app.

    That same View would look like this in ES6:

    class Counter extends Backbone.View {
    constructor() {
    super();
    this.model = new Backbone.Model({ count: 0 });
    this.tagName = "div";
    this.template = ({ count }) => `${count} <button>++</button>`;
    this.events = {
    "click button": "buttonClick",
    };
    this.listenTo(this.model, "change", this.render);
    }
    render() {
    this.$el.html(this.template(this.model.attributes));
    }
    buttonClick() {
    this.model.set({ count: this.model.get("count") + 1 });
    }
    }

    We used constructor instead of initialize, and we moved all of the properties into that function. We also used ES6 template strings instead of Handlebars for templating, and we didn’t have to write function even once.

    It’s the same amount of code, the same amount of logic, a marginal improvement in styling, and the dubious usefulness of subclassing. Big whoop.

    Every other part of your codebase, new or old, can use this View the same as a traditional ES5 Backbone View. Or it can subclass. That part is easier.

    But… why do this?

    It feels good.

    Did you enjoy this article?

    Published on September 1st, 2016 in backbone, es6, Front End, Technical

    Learned something new?
    Want to become an expert?

    Here's how it works 👇

    Leave your email and I'll send you thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.

    Join Swizec's Newsletter

    And get thoughtful letters 💌 on mindsets, tactics, and technical skills for your career. Real lessons from building production software. No bullshit.

    "Man, love your simple writing! Yours is the only newsletter I open and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌"

    ~ Ashish Kumar

    Join over 14,000 engineers just like you already improving their careers with my letters, workshops, courses, and talks. ✌️

    Have a burning question that you think I can answer? I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

    Ready to Stop copy pasting D3 examples and create data visualizations of your own?  Learn how to build scalable dataviz components your whole team can understand with React for Data Visualization

    Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.

    Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first 💰 on the side with ServerlessReact.Dev

    Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

    By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️

    Created by Swizec with ❤️