How to create an event handler which can access to structure values?

30 views Asked by At

I have a controller (name is "Instance") with a event handler manager.

I have some others controllers (the type isn't fixed) which contains some informations.

When controller "instance" calls handler function, the callback function must access to informations of others controller.

What is the best way to do it?

I do it but I don't know if it is the best way:

package main

import (
    "fmt"
    "time"
)

// ******************************************
type SetEvent func(val int)

type Instance struct {
    handlers []SetEvent
}

func NewInstance() *Instance {
    ins := Instance{}
    ins.handlers = make([]SetEvent, 0)
    return &ins
}

func (ins *Instance) AddHandler(handler SetEvent) {
    ins.handlers = append(ins.handlers, handler)
}

func (ins *Instance) Start() {
    go func() {
        i := 0
        for {
            for j := range ins.handlers {
                ins.handlers[j](i)
            }
            i++
            time.Sleep(time.Second)
        }
    }()
}

// *******************************************
type Instance2 struct {
    val int
}

func NewInstance2(val int) *Instance2 {
    ins := Instance2{}
    ins.val = val
    return &ins
}

// *******************************************
type Instance3 struct {
    str string
}

func NewInstance3(val string) *Instance3 {
    ins := Instance3{}
    ins.str = val
    return &ins
}

// *******************************************
func main() {
    b := NewInstance2(10)
    c := NewInstance3("Hello")

    a := NewInstance()

    a.AddHandler(func(val int) {
        fmt.Printf("Instance2.SetEvent %d / %d\n", val, b.val)
    })
    a.AddHandler(func(val int) {
        fmt.Printf("Instance3.SetEvent %d / %s\n", val, c.str)
    })

    a.Start()

    for {
        fmt.Printf("Main.run\n")
        time.Sleep(time.Second)
    }
}

https://go.dev/play/p/6lEOwGT1gjg

0

There are 0 answers