github.com/TeaOSLab/EdgeNode@v1.3.8/internal/events/utils.go (about)

     1  package events
     2  
     3  import (
     4  	teaconst "github.com/TeaOSLab/EdgeNode/internal/const"
     5  	"sync"
     6  )
     7  
     8  type Callbacks = []func()
     9  
    10  var eventsMap = map[Event]map[interface{}]Callbacks{} // event => map[event key][]callback
    11  var locker = sync.Mutex{}
    12  
    13  var eventKeyId = 0
    14  
    15  func NewKey() interface{} {
    16  	locker.Lock()
    17  	defer locker.Unlock()
    18  	eventKeyId++
    19  	return eventKeyId
    20  }
    21  
    22  // On 增加事件回调
    23  func On(event Event, callback func()) {
    24  	OnKey(event, nil, callback)
    25  }
    26  
    27  func OnEvents(events []Event, callback func()) {
    28  	for _, event := range events {
    29  		On(event, callback)
    30  	}
    31  }
    32  
    33  func OnClose(callback func()) {
    34  	On(EventQuit, callback)
    35  	On(EventTerminated, callback)
    36  }
    37  
    38  // OnKey 使用Key增加事件回调
    39  func OnKey(event Event, key interface{}, callback func()) {
    40  	if key == nil {
    41  		key = NewKey()
    42  	}
    43  
    44  	locker.Lock()
    45  	defer locker.Unlock()
    46  
    47  	m, ok := eventsMap[event]
    48  	if !ok {
    49  		m = map[interface{}]Callbacks{}
    50  		eventsMap[event] = m
    51  	}
    52  	m[key] = append(m[key], callback)
    53  }
    54  
    55  // Remove 删除事件回调
    56  func Remove(key interface{}) {
    57  	if key == nil {
    58  		return
    59  	}
    60  
    61  	locker.Lock()
    62  	for k, m := range eventsMap {
    63  		_, ok := m[key]
    64  		if ok {
    65  			delete(m, key)
    66  			eventsMap[k] = m
    67  		}
    68  	}
    69  	locker.Unlock()
    70  }
    71  
    72  // Notify 通知事件
    73  func Notify(event Event) {
    74  	// 特殊事件
    75  	switch event {
    76  	case EventQuit:
    77  		teaconst.IsQuiting = true
    78  	case EventTerminated:
    79  		teaconst.IsQuiting = true
    80  	}
    81  
    82  	locker.Lock()
    83  	m := eventsMap[event]
    84  	locker.Unlock()
    85  
    86  	for _, callbacks := range m {
    87  		for _, callback := range callbacks {
    88  			callback()
    89  		}
    90  	}
    91  }