Commit 9feacd46 authored by Jean-Philippe Steinmetz's avatar Jean-Philippe Steinmetz
Browse files

Adding @Init decorator to ObjectDecorators. ObjectFactory now calls @Init...

Adding @Init decorator to ObjectDecorators. ObjectFactory now calls @Init functions during initialization.
parent 77581929
......@@ -180,6 +180,44 @@ export default class ObjectFactory {
proto = Object.getPrototypeOf(proto);
}
// Call any @Init functions
const initFuncs: Function[] = this.getInitMethods(obj);
for (const func of initFuncs) {
func.bind(obj)();
}
}
/**
* Searches an object for one or more functions that implement a `@Init` decorator.
*
* @param obj The object to search.
* @returns The list of functions that implements the `@Init` decorator if found, otherwise undefined.
*/
public getInitMethods(obj: any): Function[] {
const results: Function[] = [];
for (const member in obj) {
const initialize: boolean = Reflect.getMetadata("axr:initialize", obj, member);
if (initialize) {
results.push(obj[member]);
break;
}
}
let proto = Object.getPrototypeOf(obj);
while (proto) {
for (const member of Object.getOwnPropertyNames(proto)) {
const initialize: boolean = Reflect.getMetadata("axr:initialize", proto, member);
if (initialize) {
results.push(obj[member]);
break;
}
}
proto = Object.getPrototypeOf(proto);
}
return results;
}
/**
......
......@@ -32,6 +32,15 @@ export function Inject(type: any, name: string | undefined = "default", ...args:
};
}
/**
* Apply this to a function to be executed once a new object instance has been created and all dependencies injected.
* Note: If the decorated function returns a Promise it is not gauranteed to finish execution before the object is
* returned during the instantiation process.
*/
export function Init(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
Reflect.defineMetadata("axr:initialize", true, target, propertyKey);
}
/**
* Apply this to a property to have the global configuration object injected at instantiation.
*/
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment