2011-12-03 23:55:45 +04:00
Event system
============
2011-12-09 00:21:44 +04:00
Generic library provides `` generic.event `` module which helps you implement
event systems in your application. By event system I mean an API for
2019-11-17 00:13:56 +03:00
*subscribing* for some types of events and to *handle* those events so previously
2011-12-09 00:21:44 +04:00
subscribed *handlers* are being executed.
.. contents ::
:local:
Basic usage
-----------
First you need to describe event types you want to use in your application,
`` generic.event `` dispatches events to corresponding handlers by inspecting
events' types, so it's natural to model those as classes::
2019-11-17 00:51:31 +03:00
>>> class CommentAdded(object):
... def __init__(self, post_id, comment):
... self.post_id = post_id
... self.comment = comment
2011-12-09 00:21:44 +04:00
Now you want to register handler for your event type::
2019-11-17 00:51:31 +03:00
>>> from generic.event import Manager
2011-12-09 00:21:44 +04:00
2019-11-17 00:51:31 +03:00
>>> manager = Manager()
2019-11-17 00:13:56 +03:00
2019-11-17 00:51:31 +03:00
>>> @manager.subscriber(CommentAdded)
... def print_comment(ev):
... print(f"Got new comment: {ev.comment}")
2011-12-09 00:21:44 +04:00
2019-11-17 00:13:56 +03:00
Then you just call `` generic.event.handle `` function with `` CommentAdded ``
2011-12-09 00:21:44 +04:00
instance as its argument::
2019-11-17 00:51:31 +03:00
>>> manager.handle(CommentAdded(167, "Hello!"))
Got new comment: Hello!
2011-12-09 00:21:44 +04:00
This is how it works.
Event inheritance
-----------------
Using per-application event API
-------------------------------
2011-12-09 00:38:12 +04:00
API reference
-------------
.. autoclass :: generic.event.Manager
2019-11-17 00:13:56 +03:00
:members: subscribe, subscriber, handle, unsubscribe
2011-12-09 00:38:12 +04:00
Functions below are just aliases for methods of globally instantiated
manager:
.. autofunction :: generic.event.subscribe(handler, event_type)
.. autofunction :: generic.event.subscriber(event_type)
2019-11-17 00:13:56 +03:00
.. autofunction :: generic.event.handle(event)
2011-12-09 00:38:12 +04:00
.. autofunction :: generic.event.unsubscribe(handler, event_type)