Is there a way to call an Ember Octane component method with parameters and have it return the text without implementing a helper?

38 views Asked by At

On Ember Octane versions, how would I call a method in the component.js so that it simply returns the string value into the hbs template (without creating a helper)?

For example, I want for each item in the list, pass the index value as a parameter into the randomColorClass() method in order to generate a random number between 0 and index value. I understand I could implement a new helper for it, but is there a way to simply do it direct in the component.js?

The reason I'm hesitant to use a helper is because helpers are "global" naturally and this color class is unique to and defined in this component only.

Component.js

randomColorClass(max) {
  const rand = Math.random() * max;
  return `color-${Math.floor(rand)}`;
}

Template.hbs

{{#each this.list as |item index|}}
  <div class={{this.randomColorClass index}}>
    Hi, my name is {{item.name}}
  </div>
{{/each}}
1

There are 1 answers

0
NullVoxPopuli On

As of [email protected], helpers may or may not be global.

see: https://guides.emberjs.com/release/in-depth-topics/rendering-values/

It's perfectly fine for your randomColorClass to be in your component, and invoked from your component's template.

You can do this with helpers, modifiers, and components -- anything that you can get a reference to you can directly render/invoke that reference.

It's the primary feature that allows most of what's in the modern ember tutorial to work, here: https://tutorial.glimdown.com


As long as you have at least [email protected], and if you have at least [email protected], your example code should "just work".

If you have less than [email protected], you'll need a polyfill: https://github.com/ember-polyfills/ember-functions-as-helper-polyfill

If you have less than [email protected], your only option is a global helper.


Unrelated, but I do recommend you move from pod-components to co-located octane components. (if you want to keep the folder nesting, rename both files to index.js and index.hbs, respectively)