Destructuring Parameters in Ember.Helpers

Sean Doyle

With the recent release of Ember.js version 1.13 comes support for a new API for declaring helpers.

One approach creates a helper class via Ember.Helper’s .extend, while the other declares the helper with a shorthand API via the Ember.Helper.helper function.

At the core of both approaches is the compute function.

This function accepts an array of parameters, as well as a hash of options, populated when invoked in a Handlebars template:

{{address "1600 Pennsylvania Ave" "Washington, DC" "20500" separator="<br>"}}

The corresponding JavaScript would look like this:

import Ember from 'ember';

export default Ember.Helper.helper(
  function compute(params, hash) {
    const street = params[0];
    const cityAndState = params[1];
    const zipCode = params[2];
    const separator = hash.separator;

    // ... do the work
  }
);

Using ES2015 destructuring, the variable declarations can be moved to the function‘s parameter list:

import Ember from 'ember';

export default Ember.Helper.helper(
  function compute([street, cityAndState, zipCode], { separator }) {
  // ... do the work
});

While this works great for Ember.Helper, there is nothing stopping you from using this anywhere your functions accept arrays of arguments or hashes of options:

function calculateArea({ width, height }) {
  return width * height;
}

// call it with a hash
const rectangle = { width: 5, height: 4 };

calculateArea(rectangle); // => 20

Further Reading

About thoughtbot

We've been helping engineering teams deliver exceptional products for over 20 years. Our designers, developers, and product managers work closely with teams to solve your toughest software challenges through collaborative design and development. Learn more about us.