Advertisement
Guest User

Untitled

a guest
Dec 7th, 2016
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. type ValidationError = string;
  2.  
  3.  
  4. type FieldStates<TForm> = {[Field in keyof TForm]: FieldState<TForm[Field]>}
  5.  
  6. class FieldState<TField> {
  7. private validator: (val:TField) => ValidationError|null = fTrue
  8. @observable focused = false
  9. @observable changed = false
  10. @observable finisedEditing = false;
  11.  
  12. @computed get value():TField {
  13. return this.obj[this.key];
  14. }
  15. constructor(private obj:any, private key: string) {}
  16.  
  17. @computed get error() {
  18. return this.validator(this.value)
  19. }
  20.  
  21. @computed get visibleError(): ValidationError | null {
  22. return (this.finisedEditing || null) && this.error
  23. }
  24. }
  25.  
  26. type Booleans<TForm> = {[Field in keyof TForm]: boolean}
  27.  
  28. function fTrue<T>(t:T):ValidationError|null {
  29. return null;
  30. }
  31. class Form<T> {
  32. private $_state: FieldStates<T> = {} as any;
  33.  
  34. public get $state():FieldStates<T> {
  35. if (!this.$_state) {
  36. this.$reset()
  37. }
  38. return this.$_state;
  39. }
  40.  
  41. public $reset() {
  42. let self = this;
  43. Object.keys(this).forEach(key => {
  44. (this.$_state as any)[key] = new FieldState(self, key);
  45. })
  46. }
  47.  
  48. public $handlers = {
  49. onChange: (key: string, value: any) => {
  50. (this as any)[key] = value;
  51. var $s = this.$state[key as any];
  52. $s.changed = true;
  53. },
  54. onFocus: (key: string, value: any) => {
  55. var $s = this.$state[key as any];
  56. $s.focused = true;
  57. },
  58. onBlur: (key: string, value: any) => {
  59. var $s = this.$state[key as any];
  60. if ($s.changed ) {
  61. $s.finisedEditing = true;
  62. }
  63. $s.focused = false;
  64. }
  65. }
  66. }
  67.  
  68. class Person extends Form<Person> {
  69. @observable name: string;
  70. @observable birthday: Date;
  71. }
  72.  
  73. let p = new Person();
  74.  
  75.  
  76. p.name + "-" + p.birthday.toString()
  77.  
  78. p.$state.name.error
  79. p.$state.birthday.error
  80. p.$state.birthday.visibleError
  81. p.$state.birthday.changed
  82. p.$state.birthday.focused
  83.  
  84. let elem = <input type="text" value={p.name} {...p.$handlers} />
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement