Swizec Teller - a geek with a hatswizec.com

Senior Mindset Book

Get promoted, earn a bigger salary, work for top companies

Senior Engineer Mindset cover
Learn more

    Backbone with ES6

    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.

    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.

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

    Did you enjoy this article?

    Continue reading about Backbone with ES6

    Semantically similar articles hand-picked by GPT-4

    Senior Mindset Book

    Get promoted, earn a bigger salary, work for top companies

    Learn more

    Have a burning question that you think I can answer? Hit me up on twitter and I'll do my best.

    Who am I and who do I help? I'm Swizec Teller and I turn coders into engineers with "Raw and honest from the heart!" writing. No bullshit. Real insights into the career and skills of a modern software engineer.

    Want to become a true senior engineer? Take ownership, have autonomy, and be a force multiplier on your team. The Senior Engineer Mindset ebook can help 👉 swizec.com/senior-mindset. These are the shifts in mindset that unlocked my career.

    Curious about Serverless and the modern backend? Check out Serverless Handbook, for frontend engineers 👉 ServerlessHandbook.dev

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

    Want to get my best emails on JavaScript, React, Serverless, Fullstack Web, or Indie Hacking? Check out swizec.com/collections

    Did someone amazing share this letter with you? Wonderful! You can sign up for my weekly letters for software engineers on their path to greatness, here: swizec.com/blog

    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 ❤️