tdatabind.nim 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. discard """
  2. disabled: true
  3. """
  4. import events
  5. type
  6. TProperty*[T] = object of TObject
  7. getProc: proc(property: TProperty[T]): T {.nimcall.}
  8. setProc: proc(property: var TProperty[T], value: T) {.nimcall.}
  9. value: T
  10. ValueChanged*: TEventHandler
  11. Binders: seq[TProperty[T]]
  12. EEmitter: TEventEmitter
  13. # Not a descriptive name but it was that or TPropertyValueChangeEventArgs.
  14. TValueEventArgs[T] = object of TEventArgs
  15. Property*: TProperty[T]
  16. proc newProperty*[T](value: T): TProperty[T] =
  17. var prop: TProperty[T]
  18. prop.EEmitter = initEventEmitter()
  19. prop.Binders = @[]
  20. prop.ValueChanged = initEventHandler("ValueChanged")
  21. prop.value = value
  22. proc getter(property: TProperty[T]): T =
  23. return property.value
  24. prop.getProc = getter
  25. proc setter(property: var TProperty[T], v: T) =
  26. property.value = v
  27. # fire event here
  28. var args: TValueEventArgs[T]
  29. args.Property = property
  30. property.EEmitter.emit(property.ValueChanged, args)
  31. prop.setProc = setter
  32. return prop
  33. proc `prop`[T] (p: TProperty[T]): T =
  34. # I'm assuming this is trying to get a value from the property.
  35. # i.e. myVar = myProperty
  36. return p.getProc(p)
  37. proc `~=`[T] (p: var TProperty[T], v: T) =
  38. # Assuming this is setting the value.
  39. p.setProc(p, v)
  40. proc `$`[T] (p: TProperty[T]): string =
  41. var value = p.getProc(p)
  42. return $value
  43. proc propertyBind*[T](p1: var TProperty[T], p2: var TProperty[T]) =
  44. p1.Binders.add(p2)
  45. # make handler -> handler[T] so trigger even more generics bugs ...
  46. proc handler(e: TEventArgs) =
  47. type TEA = TValueEventArgs[T]
  48. var args = TEA(e)
  49. var val = args.Property.getProc(p1)
  50. for i in countup(0, len(e.Property.ValueChanged.Binders) -1):
  51. var binded = e.Property.ValueChanged.Binders[i]
  52. binded.setProc(binded, val)
  53. echo("Property 1 has changed to " & $val)
  54. if p1.ValueChanged.containsHandler(handler) == false:
  55. addHandler(p1.ValueChanged, handler)
  56. proc `->`[T](p1: var TProperty[T], p2: var TProperty[T]) =
  57. propertyBind(p2,p1)
  58. when isMainModule:
  59. # Initial value testing
  60. var myProp = newProperty(5)
  61. echo(myProp)
  62. myProp ~= 7 # Temp operator until overloading of '=' is implemented.
  63. echo(myProp)
  64. # Binding testing
  65. var prop1 = newProperty(9)
  66. var prop2: TProperty[int]
  67. prop2 -> prop1 # Binds prop2 to prop1
  68. prop1 ~= 7
  69. echo(prop2) # Output: 7