Friday, July 3, 2009

Subscribing To Event Subscritions In Python

New in the latest version of the boduch Python library is the Subscription class. This abstraction is used to represent active event subscriptions to event handles. A Subscription instance ties together the Event class and the Handle class. The Handle providing the callback functionality that is executed when a given event takes place that the handle as a subscription to. As with previous versions, the event handle still uses the subscribe() function to subscribe to particular events. However, in previous versions, this function didn't actually return anything. The function will now return a Subscription instance. This functionality was added so that developers can have an easier method in which to reference which events will cause a given behavior to take place. The following is an example of a Subscription instance being returned.
#Example; Subscribing to a boduch Set event.

#Import required objects.
from boduch.event import subscribe, EventSetPush
from boduch.handle import Handle
from boduch.data import Set

#Simple handle.
class MyHandle(Handle):
def __init__(self, *args, **kw):
Handle.__init__(self, *args, **kw)

def run(self):
print "Running my handle."

if __name__=="__main__":
#Create a new subscription instance by subscribing to the event.
print "Subscribing"
sub=subscribe(EventSetPush, MyHandle)
print "Subscribed", sub

#Make sure the simple handle works.
Set().push("data")
In the example above, we define a simple event handle called MyHandle. We then subscribe this handle to the EventSetPush event to instantiate a new Subscription instance. Each Subscription instance holds a reference to both the handle and the event that the handle has subscribed to. Additionally, Subscription instances also define behavior. Since a Subscription instance holds a reference to the given event, we can use this instance hold build further subscriptions for this event. The core event handles inside the library already define and expose Subscription instances and can be used to create subscriptions for new event handles as the example below illustrates.
#Example; Subscribing to a boduch Set event via subscription.

#Import required objects.
from boduch.subscription import SubSetPush
from boduch.handle import Handle
from boduch.data import Set

#Simple handle.
class MyHandle(Handle):
def __init__(self, *args, **kw):
Handle.__init__(self, *args, **kw)

def run(self):
print "Running my handle."

if __name__=="__main__":
#Create a new subscription instance by subscribing to the event.
print "Subscribing"
sub=SubSetPush.subscribe(MyHandle)
print "Subscribed", sub

#Make sure the simple handle works.
Set().push("data")

No comments :

Post a Comment