Helper functions
are JavaScript functions that you can call from your template.
Ember's template syntax limits what you can express to keep the structure of your application clear at a glance. When you need to compute something using JavaScript, you can use helper functions. It's possible to create your own helpers or
just use the built-in ones.
For instance, let's take a look at a generic message component from a messaging app.
app/components/message.hbs :
<Message::Avatar
@title={{@avatarTitle}}
@initial={{@avatarInitial}}
@isActive={{@userIsActive}}
class={{if @isCurrentUser "current-user"}}
/>
<section>
<Message::Username
@name={{@username}}
@localTime={{@userLocalTime}}
/>
{{yield}}
</section>
<Message
@username="Tomster"
@userIsActive={{true}}
@userLocalTime="4:56pm"
@avatarTitle="Tomster's avatar"
@avatarInitial="T"
>
<p>
Hey Zoey, have you had a chance to look at the EmberConf
brainstorming doc I sent you?
</p>
</Message>
By looking at how we use the <Message>
component, we can see that some of the arguments are fairly repetitive. Both @avatarTitle
and @avatarInitial
are based on the user's @username
, but the title has more text, and the initial is only the first letter of the name. We'd rather just pass a username to the <Message>
component and compute the value of the title and initial.
Let's update the component to do that. It'll take a @username
argument and calculate the title and initial.