3.3
Trait Events
The Traits package defines a special type of trait called
an event. Events are instances of (subclasses of) the Event class.
There are two major differences between a normal trait and
an event:
·
All notification handlers associated with an event are called
whenever any value is assigned to the event. A
normal trait attribute only calls its associated notification handlers when the
previous value of the attribute is different from the new value being assigned
to it.
·
An event does not use any storage, and in fact does not store the
values assigned to it. Any value assigned to an event is reported as the new value to all associated notification handlers, and
then immediately discarded. Because events do not retain a value, the old argument to a notification handler associated with
an event is always the special Undefined object (see Section 3.4). Similarly,
attempting to read the value of an event results in a TraitError exception,
because an event has no value.
As an example of an event, consider:
# event.py --- Example of trait event
from
enthought.traits.api import Event, HasTraits, List, Tuple
point_2d =
Tuple(0, 0)
class
Line2D(HasTraits):
points =
List(point_2d)
line_color = RGBAColor('black')
updated
= Event
def
redraw():
pass
# Not implemented for this example
def
_points_changed():
self.updated = True
def
_updated_fired():
self.redraw()
In support of the use of events, the Traits package
understands attribute-specific notification handlers with names of the form _name_fired(), with signatures identical to the _name_changed() functions. In fact, the Traits package
does not check whether the trait attributes that _name_fired()
handlers are applied to are actually events. The function names are simply
synonyms for programmer convenience.
Similarly, a function named on_trait_event() can be used
as a synonym for on_trait_change() for dynamic notification.
|