'''
Author: your name
Date: 2021-06-15 17:40:14
LastEditTime: 2021-06-30 17:22:44
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: \evm-store\tools\resources\webcreator\event.py
'''
# -*- coding: utf_8 -*-

############################
#   信号槽
############################

class PySignal(object):
    """
    Simple event class used to provide hooks for different types of events in Locust.

    Here's how to use the EventHook class::

        my_event = PySignal()
        def on_my_event(a, b, **kw):
            print "Event was fired with arguments: %s, %s" % (a, b)
        my_event += on_my_event
        my_event.fire(a="foo", b="bar")
        my_event.emit(a="foo", b="bar")

    """

    def __init__(self):
        self._handlers = []

    def __iadd__(self, handler):
        return self.connect(handler)

    def __isub__(self, handler):
        return self.disconnect(handler)

    def connect(self, handler):
        self._handlers.append(handler)
        return self

    def disconnect(self, handler):
        self._handlers.remove(handler)
        return self

    def fire(self, *args, **kwargs):
        
        return self.emit(*args, **kwargs)

    def emit(self, *args, **kwargs):
        rets = {}
        for handler in self._handlers:
            ret = handler(*args, **kwargs)
            rets[handler.__name__] = ret
        if len(rets) == 1:
            return list(rets.values())[0]  # list()用来兼容python3
        return rets


if __name__ == '__main__':
    my_event = PySignal()

    def on_my_event(a, b, **kw):
        print(a, b)
        print(kw)
    my_event.connect(on_my_event)
    my_event.fire(1, 2, c="foo", d="bar")
    my_event.emit(3, 4, e="foo", f="bar")
