[ create a new paste ] login | about

Link: http://codepad.org/ZkZaMSjH    [ raw code | output | fork ]

Python, pasted on Feb 8:
class EventArgs(object):
    def __init__(self):
        self.handled = False

class Event(object):
    def __init__(self):
        self.__handlers = []
    def __del__(self):
        self.removeall()
    def add(self, handler):
        if callable(handler):
            if handler not in self.__handlers:
                self.__handlers.append(handler)
        return self
    def remove(self, handler):
        if callable(handler):
            if handler in self.__handlers:
                self.__handlers.remove(handler)
        return self
    __iadd__ = add
    __isub__ = remove
    def removeall(self):
        while len(self.__handlers) > 0:
            self.__handlers.pop()
        return self
    def trigger(self, sender, args):
        if len(self.__handlers) > 0:
            for f in self.__handlers:
                f(sender, args)
                if args.handled:
                    break
    __call__ = trigger

ev = Event()
sample = object()

print '----------------'
def handler(sender, args):
    print 'Handler 1'

def handler2(sender, args):
    print 'Handler 2'

ev.add(handler)
ev.trigger(sample, EventArgs())

print '----------------'
ev += handler2
ev.trigger(sample, EventArgs())

print '----------------'
def handler3(sender, args):
    print 'New handler'

ev.remove(handler)
ev -= handler2
ev.add(handler3)
ev(sample, EventArgs())

print '----------------'
def blockingHandler(sender, args):
    args.handled = True
    print 'Last handler'

def blocked(sender, args):
    print 'should not run'

ev += blockingHandler
ev += blocked
ev(sample, EventArgs())

print '----------------'
def soleHandler(sender, args):
    print 'Sole handler'

ev.removeall()
ev.add(soleHandler)
ev.trigger(sample, EventArgs())


Output:
1
2
3
4
5
6
7
8
9
10
11
12
----------------
Handler 1
----------------
Handler 1
Handler 2
----------------
New handler
----------------
New handler
Last handler
----------------
Sole handler


Create a new paste based on this one


Comments: