Implementing Routes in Ember Addon

648 Views Asked by At

I am new to ember. I am planning to create an addon to share across the application. My addon having screens to navigate. I have no idea how to apply the routes or implementing routes inside ember addon. And moreover, I want to share the addon with consuming applications also. Can anyone suggest any simple example of how to implement?

2

There are 2 best solutions below

1
On

Choosing Ember Add-on for functionality sharing is a good call. However, add-ons are mainly used to add/enhance more focused functionalities.

In order to reuse/share pages (routes) across application, Ember has an specific solution called Ember-Engines.

As per the official guide,

Engines allow multiple logical applications to be composed together into a single application from the user's perspective.

Thus, we can have multiple pages (similar to any other standalone Ember App) inside Engines and mount those pages inside the host applications with ease.

3
On

The app folder of an Ember Addon is merged with the app folder of the consuming application. While this is mostly used to provide components and services it's working the same for routes, controllers and route templates. The only tricky bit of sharing providing routes via an Ember Addon is registering them.

There are two solutions to register a route provided by an Ember Addon:

  1. Export a method from the Ember Addon that should be used by consuming application to register the routes in the router.
  2. Import the application router in an instance initalizier provided by the Addon and register the routes on it.

The first approach looks like this:

// in addon: /addon/index.js

export function registerRoutes(router) {
  router.map(function () {
    this.route('foo');
  });
}
// in consuming application: /app/router.js

import EmberRouter from '@ember/routing/router';
import config from './config/environment';
import { registerRoutes } from 'my-addon';

const Router = EmberRouter.extend({
  location: config.locationType,
  rootURL: config.rootURL
});

Router.map(function() {
  // application routes are registered as usual
});

// register routes provided by addon
registerRoutes(Router);

export default Router;

The second approach is a little bit more complex but does not require any change to consuming application. You might see that as an advantage or as confusing magic that should be avoided.

// in addon: /app/instance-initaliziers/my-addon.js

// as this is merged with application's app tree, we can import files from application
import ApplicationRouter from '../router';

export function initialize() {
  // register as you would do in app/router.js
  ApplicationRouter.map(function() {
    this.route('foo');
  });
}

export default {
  initialize
};