Skip to content

Instantly share code, notes, and snippets.

@josemarluedke
Last active October 2, 2021 00:04
Show Gist options
  • Save josemarluedke/a1500885db326606f8c257654cca6c04 to your computer and use it in GitHub Desktop.
Save josemarluedke/a1500885db326606f8c257654cca6c04 to your computer and use it in GitHub Desktop.
import { getOwner } from '@ember/application';
import type RouterService from '@ember/routing/router-service';
function useService<T = unknown>(ctx: object, name: string): T {
return getOwner(ctx).lookup(`service:${name}`) as T;
}
function ref<T = unknown>(initialValue: T): Ref<T> {
return new Ref<T>(initialValue);
}
class Ref<T = unknown> {
@tracked value: T;
constructor(initialValue: T) {
this.value = initialValue;
}
}
function useRoutedDrawer(
ctx: object,
routeName: string
): {
isOpen: Ref<boolean>;
onClose: () => void;
didClose: () => void;
} {
const isOpen = ref<boolean>(true);
return {
isOpen,
onClose: (): void => {
isOpen.value = false;
},
didClose: (): void => {
const router = useService<RouterService>(ctx, 'router');
router.transitionTo(routeName);
}
};
}
@josemarluedke
Copy link
Author

Usage:

export default class MyComponent extends Component {
  drawer = useRoutedDrawer(this, 'serviceable-addresses');

  static template = hbs`
    <Drawer
      @isOpen={{this.drawer.isOpen.value}}
      @onClose={{this.drawer.onClose}}
      @didClose={{this.drawer.didClose}}
      @size="lg"
    >
      ....
    </Drawer>`;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment