Skip to content

Instantly share code, notes, and snippets.

@jordpo
Last active July 28, 2020 19:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jordpo/94af6f864ffad1928513f123070d039f to your computer and use it in GitHub Desktop.
Save jordpo/94af6f864ffad1928513f123070d039f to your computer and use it in GitHub Desktop.
Ember href-to helper with service:router logic
import Helper from '@ember/component/helper';
import { getOwner } from '@ember/application';
interface QueryParams {
isQueryParams: boolean;
values: object;
}
type Param = number | string | QueryParams | object;
export function hrefTo(context: Helper, params: Array<Param>) {
const router = getOwner(context).lookup('service:router');
if (!router._router || !router._router._routerMicrolib) return '';
return router.urlFor(...getParamsForGenerateURL(params));
}
function getParamsForGenerateURL(params: Array<Param>) {
params = params.slice(); // Create a copy
const targetRouteName = params.shift(); // The first param is always the target route name
const lastParam = params[params.length - 1] as QueryParams; // The last param might be queryParams
let queryParams;
if (lastParam && lastParam.isQueryParams) {
queryParams = params.pop()! as QueryParams;
queryParams = queryParams.values;
} else {
queryParams = {};
}
const models = params; // The remainder are the models
return [
targetRouteName,
...models,
{ queryParams },
];
}
export default Helper.extend({
compute(params: Array<Param>, namedArgs: { params?: Array<Param>}) {
if (namedArgs.params) {
return hrefTo(this, namedArgs.params);
}
return hrefTo(this, params);
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment