diff --git a/go/react/react.go b/go/react/react.go index 2d3b512..e042293 100644 --- a/go/react/react.go +++ b/go/react/react.go @@ -1,10 +1,5 @@ package react -import ( - "fmt" - "strconv" -) - const testVersion = 4 // MyReactor implements Reactor @@ -16,7 +11,6 @@ type MyReactor struct { // New creates a new Reactor func New() *MyReactor { r := &MyReactor{} - //r.callbacks = make(map[Cell][]func(int)) return r } @@ -33,6 +27,7 @@ func (r *MyReactor) CreateCompute1(c Cell, f func(int) int) ComputeCell { r.lastId++ cc := &MyCell{id: r.lastId, isComputed: true} cc.compVal = func() int { return f(c.Value()) } + c.(*MyCell).addDependent(cc) return cc } @@ -42,6 +37,8 @@ func (r *MyReactor) CreateCompute2(c1, c2 Cell, f func(int, int) int) ComputeCel r.lastId++ cc := &MyCell{id: r.lastId, isComputed: true} cc.compVal = func() int { return f(c1.Value(), c2.Value()) } + c1.(*MyCell).addDependent(cc) + c2.(*MyCell).addDependent(cc) return cc } @@ -53,6 +50,8 @@ type MyCell struct { compVal func() int lastCallbackId int callbacks map[int]func(int) + dependents []Cell + previousVal int } // Value returns the value of the cell @@ -69,23 +68,36 @@ func (c *MyCell) SetValue(i int) { // No change or this is a computed cell, just return return } + c.previousVal = c.val c.val = i - // Hit all callbacks - for _, v := range c.callbacks { - fmt.Println("Hitting a callback: " + strconv.Itoa(i)) - v(i) + c.updated() +} + +func (c *MyCell) updated() { + if c.Value() == c.previousVal { + return } + c.previousVal = c.Value() + // Triggers callbacks + for _, v := range c.callbacks { + v(c.Value()) + } + // Hit 'updated' on all dependents + for _, v := range c.dependents { + v.(*MyCell).updated() + } +} + +func (c *MyCell) addDependent(nc Cell) { + c.dependents = append(c.dependents, nc) } func (c *MyCell) AddCallback(cb func(int)) CallbackHandle { if c.lastCallbackId == 0 { - fmt.Println("Initializing Callback Map (Cell " + strconv.Itoa(c.id) + ")") c.callbacks = make(map[int]func(int)) } - fmt.Println("Adding a Callback to " + strconv.Itoa(c.id)) c.lastCallbackId++ c.callbacks[c.lastCallbackId] = cb - fmt.Println("Number of Callbacks: " + strconv.Itoa(c.lastCallbackId)) return c.lastCallbackId }