Advertisement
Guest User

Untitled

a guest
Jan 12th, 2017
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. import {createFactory, arrayOf, onPatch, getSnapshot, applySnapshot, onSnapshot, applyPatches, IModelFactory, unionOf, primitiveFactory} from 'mobx-state-tree'
  2.  
  3. const Patch = createFactory({
  4. op: '',
  5. path: '',
  6. value: ''
  7. })
  8.  
  9. function createForm(Factory){
  10. const F = createFactory({
  11. value: Factory,
  12. binding: Factory,
  13. patches: arrayOf(Patch)
  14. })
  15.  
  16. return (state?, env?) => {
  17. const instance = F()
  18. let inRestore = false
  19.  
  20. const getValueSnapshot = () =>
  21. getSnapshot(instance.value === null ? Factory() : instance.value )
  22.  
  23.  
  24. instance.value = !!state && !!state.value ? Factory(state.value) : Factory()
  25. instance.binding = Factory(getValueSnapshot())
  26.  
  27. const runInRestore = fn => (...args) => {
  28. if(inRestore) return
  29. inRestore = true
  30. const value = fn(...args)
  31. inRestore = false
  32. return value
  33. }
  34.  
  35. onPatch(instance.binding, runInRestore(patch => {
  36. instance.patches.push(Patch(patch))
  37. }))
  38.  
  39. onSnapshot(instance, runInRestore(snapshot => {
  40. const newInstance = Factory(getValueSnapshot())
  41. applyPatches(newInstance, instance.patches.slice() as any[])
  42. applySnapshot(instance.binding, getSnapshot(newInstance))
  43. }))
  44.  
  45. return instance
  46. }
  47. }
  48.  
  49. const User = createFactory({
  50. name: '',
  51. password: ''
  52. })
  53.  
  54. const UserForm = createForm(User)
  55.  
  56. const form = UserForm()
  57.  
  58. form.binding.password = 'mattia'
  59.  
  60. form.value = User({name: 'michel'})
  61.  
  62. console.log(getSnapshot(form), getSnapshot(form.binding))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement