| 1 | """ |
| 2 | This example demonstrates an alternative way to register an event type. |
| 3 | The original way looks like this: |
| 4 | |
| 5 | class Foo(EventDispatcher): |
| 6 | # ... |
| 7 | |
| 8 | |
| 9 | Foo.register_event_type('bar') |
| 10 | |
| 11 | Instead of calling the classmethod register_event_type() below the implementation of your dispatcher, |
| 12 | you can decorate the latter with the function decorator: |
| 13 | |
| 14 | @register_event_type('bar') |
| 15 | class Foo(EventDispatcher): |
| 16 | # ... |
| 17 | |
| 18 | All in one place. |
| 19 | """ |
| 20 | |
| 21 | import pyglet |
| 22 | from pyglet.event import EventDispatcher |
| 23 | |
| 24 | |
| 25 | def register_event_type(name): |
| 26 | def _reg_evt_type(cls): |
| 27 | assert issubclass(cls, EventDispatcher), "Event types can only be registered on EventDispatcher subclasses" |
| 28 | if not hasattr(cls, 'event_types'): |
| 29 | cls.event_types = [] |
| 30 | |
| 31 | cls.event_types.append(name) |
| 32 | return cls |
| 33 | |
| 34 | return _reg_evt_type |
| 35 | |
| 36 | |
| 37 | def create_alarm(dt): |
| 38 | alarms.dispatch_event('on_wake_up', dt) |
| 39 | |
| 40 | |
| 41 | @register_event_type('on_wake_up') |
| 42 | class Alarms(EventDispatcher): |
| 43 | def on_wake_up(self, dt): |
| 44 | print(f'Yet another {dt} seconds wasted! Wake up!') |
| 45 | |
| 46 | |
| 47 | alarms = Alarms() |
| 48 | pyglet.clock.schedule_interval(create_alarm, 30) |
| 49 | pyglet.app.run() |