Class Ember.Helper
publicEmber Helpers are functions that can compute values, and are used in templates.
For example, this code calls a helper named format-currency
:
Additionally, a helper can be called as a nested helper (sometimes called a
subexpression). In this example, the computed value of a helper is passed
to a component named show-money
:
Helpers defined using a class must provide a compute
function. For example:
1 2 3 4 5 6 7 |
export default Ember.Helper.extend({ compute(params, hash) { let cents = params[0]; let currency = hash.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.
If the output of your helper is only dependent on the current input, then you
can use the Helper.helper
function.
See Ember.Helper.helper.
In this form the example above becomes:
1 2 3 4 5 |
export default Ember.Helper.helper((params, hash) => { let cents = params[0]; let currency = hash.currency; return `${currency}${cents * 0.01}`; }); |
compute (params, hash) public
Defined in packages/ember-htmlbars/lib/helper.js:94
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.
helper (helper) public
Defined in packages/ember-htmlbars/lib/helper.js:109
Available since v1.13.0
- helper
- Function
- The helper function
In many cases, the ceremony of a full Ember.Helper
class is not required.
The helper
method creates pure-function helpers without instances. For
example:
1 2 3 4 5 6 7 8 9 10 11 |
// app/helpers/format-currency.js export function formatCurrency([cents], hash) { let currency = hash.currency; return `${currency}${cents * 0.01}`; }); export default Ember.Helper.helper(formatCurrency); // tests/myhelper.js import { formatCurrency } from ..../helpers/myhelper // add some tests |
This form is more efficient at run time and results in smaller compiled js.
It is also easier to test by using the following structure and importing the
formatCurrency
function into a test.
recompute public
Defined in packages/ember-htmlbars/lib/helper.js:66
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:
1 2 3 4 5 6 7 8 9 10 |
// app/helpers/current-user-email.js export default Ember.Helper.extend({ session: Ember.inject.service(), onNewUser: Ember.observer('session.currentUser', function() { this.recompute(); }), compute() { return this.get('session.currentUser.email'); } }); |