Monday, July 26, 2010

Python - simple event programming

# simple event programming with python 
# this example is written in p3k ... but can 
# be easily ported to 2.x 
 
# Event Thrower 
class QueenBee(object):
    def __init__(self):
        self.subscriber_to_event_list = []
    def addSubscriberToEvent(self, subscriber, eventText):
        ''' subscribe bees to eventText commands ''' 
        se = (subscriber, eventText)
        self.subscriber_to_event_list.append(se)
    def issueCommand(self, eventText):
        ''' raise event to followers ''' 
        for se in self.subscriber_to_event_list:
            sub = se[0]
            eve = se[1]
            if eve == eventText:
                sub(eve)
 
# event subscriber 
class WorkerBee(object):
    def __init__(self, name, event):
        self.name = name
    def receiveEvent(self, eventName):
        ''' begin work from here ''' 
        print (self.name + " 'By Your Command,' received event: " + eventName)
 
 
 
 
 
qb = QueenBee()
# worker bees 
bList = []
# subscribe bees to commands (events) 
for i in range(10):
    bName = "b"+str(i)
    eventText = "Do More Work" 
    b = WorkerBee(bName, eventText)
    qb.addSubscriberToEvent(b.receiveEvent, eventText)
    bList.append(b)
 
# queen bee issues command that bees are not subscribed to 
print("unscribed to command output: ")
qb.issueCommand("make me a sandwhich")
# nothing happens 
 
print()
print("subscribed event issued:")
# queen bee issues subscribed to event 
qb.issueCommand("Do More Work")
 
 
 
 

No comments:

Post a Comment