Skip to content

Instantly share code, notes, and snippets.

@codediodeio
Last active February 4, 2019 22:21
Show Gist options
  • Save codediodeio/5d222897375fd1a8eeffa0f96f802983 to your computer and use it in GitHub Desktop.
Save codediodeio/5d222897375fd1a8eeffa0f96f802983 to your computer and use it in GitHub Desktop.
import { Component } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Component({
selector: 'app-root',
template: `
<p>You clicked {{count.value}} times</p>
<button (click)="setCount(count.value + 1)">Click Me</button>
`,
})
export class AppComponent {
@UseState(0) count; setCount;
@UseEffect()
onEffect() {
document.title = `You clicked ${this.count.value} times`;
}
}
/// Implementation Details:
function UseEffect() {
return function (target, key, descriptor) {
target.ngOnInit = descriptor.value;
target.ngOnChanges = descriptor.value;
};
}
function UseState(seed: any) {
return function (target, key) {
target[key] = new BehaviorSubject(seed);
target[`set${key.replace(/^\w/, c => c.toUpperCase())}`] = (val) => target.count.next(val);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment