SHARE
TWEET

Untitled

a guest Nov 19th, 2019 69 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. struct Event {
  2.     sparam string
  3. }
  4. struct EventCallback{
  5.    func fn(Event)
  6. }
  7. struct Emitter {
  8. mut:
  9.     listeners []EventCallback
  10. }
  11. //////////////////////////////////////////////////////
  12. pub fn (e Event) str() string { return 'event{ $e.sparam }' }
  13. pub fn (ec &EventCallback) str() string { return 'event_callback{ ' + ptr_str(ec.func) + ' }' }
  14. pub fn new_emitter() Emitter {
  15.     return Emitter{}
  16. }
  17. pub fn (e mut Emitter) connect(f fn(Event)) {
  18.     e.listeners << EventCallback{ f }
  19. }
  20. pub fn (e Emitter) emit( sparam string) {
  21.     event := Event{ sparam }
  22.     println('emitting event: $event ...')
  23.     for listener in e.listeners {
  24.         f := listener.func
  25.         f(event)
  26.     }
  27. }
  28. //////////////////////////////////////////////////////
  29. fn cb1(e Event){ println('cb1: $e') }
  30. fn cb2(e Event){ println('cb2: $e') }
  31.  
  32. fn main(){
  33.     mut ready_emitter := new_emitter()
  34.     ready_emitter.connect( cb1 )
  35.     ready_emitter.connect( cb2 )
  36.     ready_emitter.emit('Hello')
  37. }
  38.  
  39. /* produces:
  40. -------------------------------------------------
  41. emitting event: event{ Hello }  ...
  42. cb1: event{ Hello }
  43. cb2: event{ Hello }
  44. */
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top