NotificationCenter
This package implements a class similar to NSNotificationCenter, a variant of the Observer design pattern, from Objective-C and Swift in Python. To install, (soon you will be able to) just use
pip install notificationcenter
It consists of one singleton class, NotificationCenter, that is used to add observers and to post notifications. To add an observer, you need to do the following:
from notificationcenter import *
notificationcenter = NotificationCenter()
def foo(sender, notification_name, info):
observer = notificationcenter.add_observer(with_block=foo,
for_name="bar")
Now, if we post a notification to the NotificationCenter with the name "bar", as follows, the above function foo will be executed.
notificationcenter = NotificationCenter()
notificationcenter.post_notification(sender=None,
with_name="bar")
When you are no longer using the observer, you should remove it from the NotificationCenter so that the block is no longer executed. It is done as follows:
notificationcenter.remove_oberver(observer)
Detailed documentation is shown below, and the source code is commented.
API Reference
add_observer(with_block, for_name, for_sender=None)
Adds an observer to listen for certain types of notifications.
Parameters:
Returns:
- tuple (String, Any Object, Some Function)
- This is a tuple of (for_name, for_sender, with_block). It is not meant to be used directly except in the remove_observer method.
remove_observer(observer)
Removes the given observer from the list of active obserers.
Parameters:
- observer: tuple (String, Any Object, Some Function)
- This is the tuple that is returned by add_observer.
post_notification(sender, with_name, with_info=None)
Posts a notification with a given name and (optionally) some additional information.
Parameters:
-
sender: Any Object
- The sender of this notification
-
with_name: String
- The name of the notification
-
with_info: Any Object
- Any additional information for the notification