Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- type ValidationError = string;
- type FieldStates<TForm> = {[Field in keyof TForm]: FieldState<TForm[Field]>}
- class FieldState<TField> {
- private validator: (val:TField) => ValidationError|null = fTrue
- @observable focused = false
- @observable changed = false
- @observable finisedEditing = false;
- @computed get value():TField {
- return this.obj[this.key];
- }
- constructor(private obj:any, private key: string) {}
- @computed get error() {
- return this.validator(this.value)
- }
- @computed get visibleError(): ValidationError | null {
- return (this.finisedEditing || null) && this.error
- }
- }
- type Booleans<TForm> = {[Field in keyof TForm]: boolean}
- function fTrue<T>(t:T):ValidationError|null {
- return null;
- }
- class Form<T> {
- private $_state: FieldStates<T> = {} as any;
- public get $state():FieldStates<T> {
- if (!this.$_state) {
- this.$reset()
- }
- return this.$_state;
- }
- public $reset() {
- let self = this;
- Object.keys(this).forEach(key => {
- (this.$_state as any)[key] = new FieldState(self, key);
- })
- }
- public $handlers = {
- onChange: (key: string, value: any) => {
- (this as any)[key] = value;
- var $s = this.$state[key as any];
- $s.changed = true;
- },
- onFocus: (key: string, value: any) => {
- var $s = this.$state[key as any];
- $s.focused = true;
- },
- onBlur: (key: string, value: any) => {
- var $s = this.$state[key as any];
- if ($s.changed ) {
- $s.finisedEditing = true;
- }
- $s.focused = false;
- }
- }
- }
- class Person extends Form<Person> {
- @observable name: string;
- @observable birthday: Date;
- }
- let p = new Person();
- p.name + "-" + p.birthday.toString()
- p.$state.name.error
- p.$state.birthday.error
- p.$state.birthday.visibleError
- p.$state.birthday.changed
- p.$state.birthday.focused
- let elem = <input type="text" value={p.name} {...p.$handlers} />
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement