Class Helper
publicimport Helper from '@ember/component/helper';
Ember Helpers are functions that can compute values, and are used in templates.
For example, this code calls a helper named format-currency
:
<Cost @cents={{230}} />
<div>{{format-currency @cents currency="$"}}</div>
Additionally a helper can be called as a nested helper.
In this example, we show the formatted currency value if the showMoney
named argument is truthy.
{{if @showMoney (format-currency @cents currency="$")}}
Helpers defined using a class must provide a compute
function. For example:
import Helper from '@ember/component/helper';
export default class extends Helper {
compute([cents], { currency }) {
return `${currency}${cents * 0.01}`;
}
}
Each time the input to a helper changes, the compute
function will be
called again.
As instances, these helpers also have access to the container and will accept injected dependencies.
Additionally, class helpers can call recompute
to force a new computation.
compute (params, hash) public
Defined in packages/@ember/-internals/glimmer/lib/helper.ts:123
Available since v1.13.0
- params
- Array
The positional arguments to the helper
- hash
- Object
The named arguments to the helper
Override this function when writing a class-based helper.
recompute public
Defined in packages/@ember/-internals/glimmer/lib/helper.ts:90
Available since v1.13.0
On a class-based helper, it may be useful to force a recomputation of that
helpers value. This is akin to rerender
on a component.
For example, this component will rerender when the currentUser
on a
session service changes:
import Helper from '@ember/component/helper'
import { inject as service } from '@ember/service'
import { observer } from '@ember/object'
export default Helper.extend({
session: service(),
onNewUser: observer('session.currentUser', function() {
this.recompute();
}),
compute() {
return this.get('session.currentUser.email');
}
});