Reusing plain old javascript in component classes

Hopefully a straight forward question: where should I put plain JavaScript that I can use between a few different components?

I have a couple of different component that have a isActive property based on whether the current route maps to a route passed ot the component. Something like:

export default class MenuItemSimpleComponent extends Component {
  @service router;
  
  get isActive() {
    const route = this.args.route.split('.');
    const curr = this.router.currentRouteName.split('.');

    // from here to the end is basically POJS and could be in a reusable function somewhere
    const stripThese = ['new', 'edit', 'index', 'modal'];
    if (stripThese.includes(curr[curr.length - 1])) { curr.pop(); }

    return pluralize(route[route.length - 1]) == pluralize(curr[curr.length - 1]);
  }

To rephrase: what is the best practices for extracting out a reusable chunk of POJS in Ember 4?

There is no specific place for this kind of thing, and Ember is intentionally un-opinionated about it: there is no runtime resolution required other than just using normal JS imports. Most apps I’ve seen have something like a utils directory for small utilities, or dedicated folders with modules in them for other specific JS concerns. For your case, I would probably just put it in something like app/utils/route-helpers.js and then import the function from there and use it normally:

import { filteredActiveRouteIsActive } from '../utils/route-helpers';

export default class MenuItemSimpleComponent extends Component {
  @service router;
  
  get isActive() {
    const route = this.args.route.split('.');
    const curr = this.router.currentRouteName.split('.');

    return filteredActiveRouteIsActive(curr, route);
  }

  // ...
}
4 Likes