Array Helper (3.8)

This complement to the hash helper fills in a gap in Ember's templating API and is great for prototyping.


The array helper is a new helper for our templates:

{{array 1 2 3}}

It lets us easily create JavaScript arrays in our templates. You can think of it as a complement to the (hash) helper, which lets us create JavaScript objects in our templates.

Like other helpers it can be used in sub-expressions:

{{log (array 1 2 3)}}

One nice thing about the array helper is that it's reactive. It updates when its arguments change, just like other Handlebars primitives do. For example, if the backing context for a template had a this.count property that changed over time

<p>The count is {{this.count}}</p>

if we passed this into {{array}}, we would also see that array change over time:

{{log (array 1 2 this.count)}}
// [1, 2, 3]
// [1, 2, 4]
// [1, 2, 5]

Similarly, if we were to pass an (array) into a component, that component's didReceiveAttrs hook would fire if the array's arguments ever changed.

<SomeComponent @numbers={{array 1 2 this.count}} />

So, when should you use (array)? One good use case is for prototyping. Many addons have components that expect arrays, like Ember Power Select:

  @onchange={{action (mut this.selected)}}
as |name|>

It can break your flow to change to a JS file just to create an options property, so the array helper lets you stay inside your template and easily add some static data:

-   @options={{this.options}}
+   @options={{array 'New York' 'London' 'Tokyo'}}
    @onchange={{action (mut this.selected)}}
  as |name|>

Another use case to keep your eye out for is simpler component reuse. Often your applications will have components whose interfaces expect an array:

<CommentsList @comments={{post.comments}} />

You may find yourself in a situation where you have a single comment, say as this.model, and you'd like to reuse the <CommentsList> component.

Instead of having to update its API to accept a single comment

{{! New interface. More work! }}
<CommentsList @comment={{this.model}}>

just use the existing interface and wrap your comment in an array:

{{! Less work }}
<CommentsList @comments={{array this.model}}>

The array helper is a handy tool that every Ember should have in their arsenal.


Send us a tweet:

Or ask us in Inside EmberMap, our private Slack workspace for subscribers.