Answer the question
In order to leave comments, you need to log in
How to elegantly implement tasks on the site?
Good afternoon. I need to implement missions (for example, to pardon two players), I could write a check instruction directly in the pardon function, but then it will be very difficult to add new missions and edit old ones (scattered throughout the code). I want to do it all in one place. 1 crazy idea came to mind: send all handlers as a callback to the mission handler function
Answer the question
In order to leave comments, you need to log in
As an option.
If you use some kind of framework, then perhaps there is an event system, if not, then write your own. Further, each successful action triggers its own global event. And all the logic can already be processed in a separate component by subscribing to the events you need.
I must say right away that there will be a problem with passing arguments, especially context will be needed, but frameworks usually solve these problems.
https://play.golang.org/p/NJ-X38UrWC
In addition to a comment on another answer.
package events
import (
"sync"
)
var events *Events
type Events struct {
sync.RWMutex
list map[string]func(ps []string)
}
func NewEventsList() (list *Events) {
list = new(Events)
list.list = make(map[string]func(ps []string))
return list
}
func init() {
events = NewEventsList()
}
func Add(name string, callback func(ps []string)) {
events.Add(name, callback)
}
func Call(name string, ps []string) bool {
return events.Call(name, ps)
}
// Подписка на событие
func (l *Events) Add(name string, callback func(ps []string)) {
l.Lock()
defer l.Unlock()
l.list[name] = callback
}
// Вызов события
func (l *Events) Call(name string, ps []string) bool {
l.RLock()
defer l.RUnlock()
if f, ok := l.list[name]; ok {
go f(ps)
return true
}
return false
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question