github.com/jgarto/itcv@v0.0.0-20180826224514-4eea09c1aa0d/examples/sites/globalstate/person_viewer.go (about) 1 package main 2 3 import ( 4 "fmt" 5 6 "myitcv.io/react" 7 "myitcv.io/react/examples/sites/globalstate/model" 8 "myitcv.io/react/examples/sites/globalstate/state" 9 ) 10 11 type PersonViewerDef struct { 12 react.ComponentDef 13 } 14 15 type PersonViewerState struct { 16 p *model.Person 17 18 curPersSub *state.Sub 19 } 20 21 func PersonViewer() *PersonViewerElem { 22 return buildPersonViewerElem() 23 } 24 25 func (p PersonViewerDef) ComponentWillMount() { 26 curPersSub := state.State.CurrentPerson().Subscribe(p.currPersonUpdated) 27 28 p.SetState(PersonViewerState{ 29 p: state.State.CurrentPerson().Get(), 30 curPersSub: curPersSub, 31 }) 32 } 33 34 func (p PersonViewerDef) ComponentWillUnmount() { 35 p.State().curPersSub.Clear() 36 } 37 38 func (p PersonViewerDef) Render() react.Element { 39 st := p.State() 40 41 if st.p != nil { 42 return react.P(nil, react.S(fmt.Sprintf("You have selected %v, age %v", st.p.Name(), st.p.Age()))) 43 } 44 45 return react.P(nil, react.S("(no person selected)")) 46 } 47 48 func (p PersonViewerDef) currPersonUpdated() { 49 st := p.State() 50 st.p = state.State.CurrentPerson().Get() 51 p.SetState(st) 52 }