Skip to content

Instantly share code, notes, and snippets.

@kellegous
Created January 3, 2012 19:37
Show Gist options
  • Save kellegous/1556515 to your computer and use it in GitHub Desktop.
Save kellegous/1556515 to your computer and use it in GitHub Desktop.
package main
import "fmt"
// A simple event.
type Event int
// An interface for things that can send events.
type Dispatcher interface {
DispatchEvent(e Event)
ListenWith(f func(Dispatcher, Event))
Equals(d Dispatcher) bool
}
// A thing that dispatches and can be composited.
type disp struct {
listener func(Dispatcher, Event)
}
func (d *disp) DispatchEvent(e Event) {
d.listener(d, e)
}
func (d *disp) ListenWith(f func(Dispatcher, Event)) {
d.listener = f
}
func (d *disp) Equals(o Dispatcher) bool {
switch t := o.(type) {
case *disp:
return t == d
}
return false
}
// A concrete thing that gives off events.
type Widget struct {
disp
Id int
}
func (w *Widget) fire() {
w.Id++
w.DispatchEvent(Event(w.Id))
}
// Where it all begins.
func main() {
a := Widget{}
b := Widget{}
// a listener func
listener := func(d Dispatcher, e Event) {
if a.Equals(d) {
fmt.Printf("Event: a(%d)\n", e)
return
}
if b.Equals(d) {
fmt.Printf("Event: b(%d)\n", e)
return
}
}
a.ListenWith(listener)
b.ListenWith(listener)
a.fire()
b.fire()
}
@kellegous
Copy link
Author

Output is:
Event: a(1)
Event: b(1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment