473,387 Members | 1,585 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Events - Design Patterns

Hi there,
i found a nice article about a custom implementation of events by Duncan
Booth here:

http://www.suttoncourtenay.org.uk/du....html#observer
The code is here:

STEP 1) Define a Delegate Class

class Delegate:
'''Handles a list of methods and functions
Usage:
d = Delegate()
d += function # Add function to end of delegate list
d(*args, **kw) # Call all functions, returns a list of results
d -= function # Removes last matching function from list
d -= object # Removes all methods of object from list
'''
def __init__(self):
self.__delegates = []

def __iadd__(self, callback):
self.__delegates.append(callback)
return self

def __isub__(self, callback):
# If callback is a class instance,
# remove all callbacks for that instance
self.__delegates = [ cb
for cb in self.__delegates
if getattr(cb, 'im_self', None) != callback]

# If callback is callable, remove the last
# matching callback
if callable(callback):
for i in range(len(self.__delegates)-1, -1, -1):
if self.__delegates[i] == callback:
del self.__delegates[i]
return self
return self

def __call__(self, *args, **kw):
return [ callback(*args, **kw)
for callback in self.__delegates]STEP 2) Define the Event
Classclass Event(property):
'''Class event notifier
Usage:
class C:
TheEvent = Event()
def OnTheEvent(self):
self.TheEvent(self, context)

instance = C()
instance.TheEvent += callback
instance.OnTheEvent()
instance.TheEvent -= callback
'''
def __init__(self):
self.attrName = attrName = "__Event_" + str(id(self))
def getEvent(subject):
if not hasattr(subject, attrName):
setattr(subject, attrName, Delegate())
return getattr(subject, attrName)
super(Event, self).__init__(getEvent)

def call(self, subject, *args, **kw):
if hasattr(subject, self.attrName):
getattr(subject, self.attrName)(subject, *args, **kw)

STEP 3) Use this logic in an object (ObjectA)class ClockTimer:
def GetHour(self):
return self._hour
def GetMinute(self):
return self._minute
def GetSecond(self):
return self._second

TickEvent = Event()
def OnTick(self):
ClockTimer.TickEvent.call(self, self.GetHour(),
self.GetMinute(), self.GetSecond())

def Tick(self):
# update internal time-keeping state
# ...
self.OnTick()
STEP 4) Subscribe the ObjectA Event and react...class DigitalClock(Widget):
def __init__(self, clockTimer):
self.__subject = clockTimer
clockTimer.TickEvent += self.Update

def close(self):
self.__subject.TickEvent -= self.Update

def Update(self, subject, hour, min, sec):
self.displayedTime = (hour, min, sec)
self.Draw()

def Draw(self):
# draw the digital clock
I've tried to use it but i failed. From mypoint of view my event is never
been fired and it seem that my event subscription is not accepted and my
OnTick Event never raise to execute the Update method,i've made some changes
to the original code.. jjust inserted a timer to have this event fired many
times:class ClockTimer: _hour = 1 _minute = 1 _second = 1
_timer = Timers.timer(0) def __init__(self):
self._timer.start(10) while 1:
if(self._timer.isexpired()): self._hour = self._hour + 1
self._minute = self._minute +1 self._second = self._second +1
self.Tick() self._timer.start(10)
def getHour(self): return self._hour def getMinutes(self):
return self._minute def getSecond(self): return self._second
TickEvent = Event() def OnTick(self):
ClockTimer.TickEvent.call(self, self.getHour(), self.getMinutes(),
self.getSecond()) def Tick(self): print "Tick in CLockTimer"
self.OnTick()and a little modification to the object that uses this
event:class DigitalClock(): clockTimer = ClockTimer() def
__init__(self): clockTimer.TickEvent += self.update def
close(self): self.__subject.TickEvent -= self.update def
update(self, subject, hour, min, sec): print hour print min
print secthe code is really eas as you can see... so in the main i added
this simpleline of code...c = DigitalClock()but nothing really happen... i'm
sure i'm going wrong somewhere.. but cant understand where...any Idea???I've
tried to ask to Duncan directly by mail.. but the reported mail address is
no more valid...Someone used this?? Someone uses an other way for events???
Regards,Gianmaria

Nov 30 '07 #1
0 1059

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Design Pattern Catalog | last post by:
Thank you for your interest in "Design Patterns: Elements of Reusable Object-Oriented Design", by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. This message answers several...
13
by: John Salerno | last post by:
Here are a few I'm considering: Design Patterns Explained : A New Perspective on Object-Oriented Design (2nd Edition) (Software Patterns Series) by Alan Shalloway Design Patterns C# by...
7
by: =?Utf-8?B?bWF2cmlja18xMDE=?= | last post by:
Hi, I would like to know more about design patterns and specifically using C#. Can any one recommend a good book? Thanks
10
by: menashay | last post by:
Hello, I am absolute beginner in C# so pardon me if the following question is too easy. I have a form with a one button. When I click the button I want to display a message that reads...
10
by: vital | last post by:
Hi, I am designing the middle tier of a project. It has 6 classes and microsoft application data access block. The six classes are DBServices, Logger, ProjectServices ... etc. and all these...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.