Ember helper -pass in a n object

Isn’t it possible to pass an object to a helper instead of pass several parameters ?

I have a shop-name helper defined as follows:

import { helper } from '@ember/component/helper';

export function shopName(shop) {
  return `${shop.identifier}-${shop.name}`;
}

export default helper(shopName);

and I tried to pass in the shop object like that from a template:

{{#each model as |shop|}}
  <option value={{shop.id}}>{{shop-name shop}}</option>
{{/each}}

but it does not work, - I have undefined-undefined value displayed.

To debug I’d either put a breakpoint in the helper code.

Assuming shop is an ember data model the problem is probably the fact that you aren’t using “get” in the helper to access the identifier and name properties, you’re just treating it like a POJO.

Maybe try this?

import { helper } from '@ember/component/helper';
import { get } from `@ember/object';

export function shopName(shop) {
  return `${get(shop,'identifier')}-${get(shop,'name')}`;
}

export default helper(shopName);

Ah, my bad, - coming from Java/Rails world, I totally forgotten that in JS universe it had to be done differently. Thank you so much.

The above syntax failed:

Uncaught ReferenceError: get is not defined
    at shopName (shop-name.js:9)

:frowning:

Did you import “get”? See my solution above. Or just use shop.get

Ahr, nope, :(. In the meanwhile, I moved it to the model and used computed properties:

shopName: computed('identifier', 'name', function() {
    return `${this.get('identifier')}-${this.get('name')}`;
  })

Thank you for your help :slight_smile:

Hello @belgoros,

Your helper function signature is a bit off. When you do {{ my-helper 'one' 'two' }}, your helper function will get an array. So

export function myHelper(params) {
  // params[0] will be 'one'
  // params[1] will be 'two'
}

You can easily destruct the array in your case

import { helper } from '@ember/component/helper';

export function shopName([shop]) { // <-- Like this
  return `${shop.identifier}-${shop.name}`;
}

export default helper(shopName);

You can check the guides for some more info → Writing Helpers - Templates - Ember Guides

2 Likes

@mupkoo Thanks a lot, it is good to know. I’ll take a note of that.

Just as a note, the general best-practice around adding computed properties to models is to avoid it, when the CP is just to display something in the template. This blog post on EmberMap has some good information about when to use CPs on models and when to avoid them.

@alexlafroscia thanks a lot for the provided link, good to know.

1 Like