watson.events.dispatcher¶
- class watson.events.dispatcher.EventDispatcher[source]¶
Register and trigger events that will be executed by callables.
The EventDispatcher allows user defined events to be specified. Any listener that is triggered will have the event that was triggered passed to it as the first argument. Attributes can be added to the event params (see watson.events.types.Event) which can then be accessed by the listener.
Example:
dispatcher = EventDispatcher() dispatcher.add('MyEvent', lambda x: x.name) result = dispatcher.trigger(Event('SampleEvent')) result.first() # 'SampleEvent'
- add(event, callback, priority=1, only_once=False)[source]¶
Add an event listener to the dispatcher.
Adds an event listener to the relevant event listener collection. If a listener is set to once_only, it will be removed when the event is triggered on the EventDispatcher.
Parameters: - event (string) – The name of the event
- callback (callable) – A callable function to be triggered
- priority (int) – The priority of the listener (higher == more important)
- once_only (boolean) – When triggered, the listener will be removed
Returns: A list of listeners attached to the event
Return type: ListCollection
- has(event, callback=None)[source]¶
Return whether or not a callback is found for a particular event.
- remove(event, callback=None)[source]¶
Remove an event listener from the dispatcher.
Removes an event listener from the relevant Listener. If no callback is specified, all event listeners for that event are removed.
Parameters: - event (string) – The name of the event
- callback (callable) – A callable function to be triggered
Returns: A list of listeners attached to the event
Return type: Listener
- trigger(event)[source]¶
Fire an event and return a list of results from all listeners.
Dispatches an event to all associated listeners and returns a list of results. If the event is stopped (Event.stopped) then the Result returned will only contain the response from the first listener in the stack.
Parameters: event (watson.events.types.Event) – The event to trigger Returns: A list of all the responses Return type: Result