Last active
June 18, 2018 11:39
-
-
Save edewit/2370f51ff7966a9727357357085a562f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as _ from 'lodash'; | |
import { Broadcaster } from 'ngx-base'; | |
import { Injector } from '@angular/core'; | |
export function broadcast(event: string, properties: any): MethodDecorator { | |
return function (target: Function, methodName: string, descriptor: any) { | |
const originalMethod = descriptor.value; | |
descriptor.value = function (...args: any[]) { | |
const broadcast: Broadcaster = StaticInjector.injector.get(Broadcaster); | |
if (!broadcast) { | |
return originalMethod.apply(this, args); | |
} | |
const mapKeys = (props: any, base?: string): any => { | |
Object.keys(props).forEach(key => { | |
if (typeof properties[key] === 'object') { | |
mapKeys(properties[key], key); | |
} else { | |
properties[key] = _.get(this, (base || '') + '.' + properties[base][key]); | |
} | |
}); | |
}; | |
let props = _.cloneDeep(properties); | |
mapKeys(props); | |
broadcast.broadcast(event, props); | |
return originalMethod.apply(this, args); | |
}; | |
return descriptor; | |
}; | |
} | |
export class StaticInjector { | |
static injector: any = null; | |
constructor(injector: Injector) { | |
StaticInjector.injector = injector; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment