Hi all I am wonder if that is possible get all classes that have given decorator javascript/typescript.
I have class for example
@mydecorator
class SomeClass1{
}
and somewere else in module
@mydecorator
class SomeClass2{
}
then in other module in runtime i would like to get all classes or constructors that have decorator @mydecorator ... I am afraid that this is not possible :(
export function getaAllClassesByDecorator(decorator:string){
... return constructor or something that i am able to call static method
}
Hi all I am wonder if that is possible get all classes that have given decorator javascript/typescript.
I have class for example
@mydecorator
class SomeClass1{
}
and somewere else in module
@mydecorator
class SomeClass2{
}
then in other module in runtime i would like to get all classes or constructors that have decorator @mydecorator ... I am afraid that this is not possible :(
export function getaAllClassesByDecorator(decorator:string){
... return constructor or something that i am able to call static method
}
Share
Improve this question
edited Sep 21, 2016 at 19:20
Ivan Mjartan
asked Sep 21, 2016 at 19:09
Ivan MjartanIvan Mjartan
9871 gold badge13 silver badges25 bronze badges
5
- What exactly do you need them for? – Bergi Commented Sep 21, 2016 at 20:46
- I was look for elegant way how to globally register class and than create. Something like dependency pattern. – Ivan Mjartan Commented Sep 22, 2016 at 6:42
- 1 Doesn't the ES6 module system already give you that? – Bergi Commented Sep 22, 2016 at 6:59
- Yes, but i am developing mobile web i was looking for some general hamburger menu for each view. So my idea is add label PATH to each view/ponent than in hamburger menu ponent get all classes with attribute Path and generate menu tree structure. – Ivan Mjartan Commented Sep 22, 2016 at 7:04
- Maybe this helps: stackoverflow./questions/31618212/… – Denis Giffeler Commented Jul 26, 2021 at 7:03
2 Answers
Reset to default 14You need to "register" all classes that uses @mydecorator somewhere. This register logic should be implemented in @mydecorator. For example:
export const registeredClasses = [];
export function mydecorator() {
return function(target: Function) {
registeredClasses.push(target);
};
}
@mydecorator()
class SomeClass1{
}
@mydecorator()
class SomeClass2{
}
Now you can get all registered classes in the registeredClasses array
You can't do that "automatically", but you can create a registry with said classes.
Then inside your decorator function you add these classes:
const REGISTRY: { [name: string]: any } = {};
function mydecorator(constructor) {
REGISTRY[constructor.name] = constructor;
}
Then you can query this REGISTRY
and know who used this decorator.