Skip to content

Instantly share code, notes, and snippets.

@maraisr
Created May 14, 2018 03:23
Show Gist options
  • Save maraisr/bc07b75a0c68a396519040208a57fe66 to your computer and use it in GitHub Desktop.
Save maraisr/bc07b75a0c68a396519040208a57fe66 to your computer and use it in GitHub Desktop.
$OnChanges Angular1.6+ decorator
const ONCHANGE_LISTENERS_TYPE = 'change:listeners';
function OnChanged$ (...properties: Array<string>) {
return function targetChangeFunction (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
Reflect.defineMetadata(ONCHANGE_LISTENERS_TYPE, [
...(Reflect.getMetadata(ONCHANGE_LISTENERS_TYPE, target) || []),
{
properties,
fnc: Reflect.get(target, propertyKey)
}
], target);
target['$onChanges'] = function onChange (changes: { [property: string]: { currentValue: any, previousValue: any } }) {
console.log(63, 'index.ts',(Reflect.getMetadata(ONCHANGE_LISTENERS_TYPE, target) || []));
console.log(65, 'index.ts',Reflect.getMetadata(ONCHANGE_LISTENERS_TYPE, target));
// get a list of listeners
(Reflect.getMetadata(ONCHANGE_LISTENERS_TYPE, target) || [])
.filter(({properties}) => {
console.log(66, 'index.ts', properties);
});
// filter to only the valid ones
// execute the valid
};
/*target['$onChanges'] = function (changes: { [property: string]: { currentValue: any, previousValue: any } }) {
Object.entries(changes)
.map(([prop, delta]) => {
(Reflect.getMetadata(ONCHANGED_FNX, target) || [])
.filter(({properties}) => properties.includes(prop))
});
};*/
};
}
type TOnChangedFunc = (changes: { [property: string]: { currentValue: any, previousValue: any } }) => void;
@maraisr
Copy link
Author

maraisr commented May 24, 2018

Basic use case:

class MyComponent extends IComponent {
    events: Array<Event>;

    @OnChages$('events')
    eventsOnChage(events):void {
        // By bindings changed
    }
}

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