This commit is contained in:
Brian Buller 2016-08-15 07:26:26 -05:00
parent 50f4a86fd8
commit 2671fb5ad1

View File

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