Skip to content

Instantly share code, notes, and snippets.

@onionhammer
Created February 12, 2015 15:25
Show Gist options
  • Select an option

  • Save onionhammer/5bb2b0d2f7944cab06a5 to your computer and use it in GitHub Desktop.

Select an option

Save onionhammer/5bb2b0d2f7944cab06a5 to your computer and use it in GitHub Desktop.
Arrowlike confusion
type Pub*[T] = object
subs: seq[proc(e: T)]
proc init*[T](pub: var Pub[T]) =
if pub.subs == nil:
pub.subs = @[]
proc `()`*[T](pub: Pub, e: T) =
if pub.subs != nil:
for sub in pub.subs:
sub(e)
proc `()`*[T](pub: var Pub, sub: proc(e: T)) =
if pub.subs == nil: pub.subs = @[ sub ]
else: pub.subs.add(sub)
proc add*[T](pub: var Pub, sub: proc(e: T)) =
if pub.subs == nil: pub.subs = @[ sub ]
else: pub.subs.add(sub)
proc `&=`*[T](pub: var Pub, sub: proc(e: T)) =
if pub.subs == nil: pub.subs = @[ sub ]
else: pub.subs.add(sub)
when isMainModule:
import future
type Person = object
name: string
onSpeak: Pub[string]
proc speak(self: var Person, words: string) =
self.onSpeak(words)
proc outputSpeech(e: string) =
echo e
var a = Person()
a.onSpeak &= (s: string) => echo s
a.speak "Hello world!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment