Event API

Decorators

flexx.event.connect(*connection_strings)

Decorator to turn a method of HasEvents into an event Handler.

A method can be connected to multiple event types. Each connection string represents an event type to connect to. Read more about dynamism and labels for further information on the possibilities of connection strings.

To connect functions or methods to an event from another HasEvents object, use that object’s HasEvents.connect() method.

class MyObject(event.HasEvents):
    @event.connect('first_name', 'last_name')
    def greet(self, *events):
        print('hello %s %s' % (self.first_name, self.last_name))
flexx.event.prop(func)

Decorator to define a settable propery. An event is emitted when the property is set, which has values for “old_value” and “new_value”.

class MyObject(event.HasEvents):

   @prop
   def foo(self, v=1):
        ''' docstring goes here. '''
        return float(v)

m = MyObject(foo=2)
m.foo = 3

The method should have one argument, which can have a default value to specify the initial value of the property. The body of the method is used to do verification and normalization of the value being set. The method’s docstring is used as the property’s docstring.

flexx.event.readonly(func)

Decorator to define a readonly property. An event is emitted when the property is set, which has values for “old_value” and “new_value”. To set a readonly property internally, use the HasEvents._set_prop() method.

class MyObject(event.HasEvents):

   @readonly
   def bar(self, v=1):
        return float(v)

m = MyObject()
m._set_prop('bar', 2)  # only for internal use
flexx.event.emitter(func)

Decorator to define an emitter. An emitter is an attribute that makes it easy to emit specific events and functions as a placeholder for documenting an event.

class MyObject(event.HasEvents):

   @emitter
   def spam(self, v):
        return dict(value=v)

m = MyObject()
m.spam(42)

The method can have any number of arguments, and should return a dictionary that represents the event to generate. The method’s docstring is used as the emitter’s docstring.

HasEvents

class flexx.event.HasEvents(**property_values)

Base class for objects that have properties and can emit events. Initial values of settable properties can be provided by passing them as keyword arguments.

Objects of this class can emit events through their emit() method. Subclasses can use the prop and readonly decorator to create properties, and the connect decorator to create handlers. Methods named on_foo are connected to the event “foo”.

class MyObject(event.HasEvents):

    # Emitters

    @event.prop
    def foo(self, v=0):
        return float(v)

    @event.emitter
    def bar(self, v):
        return dict(value=v)  # the event to emit

    # Handlers

    @event.connect('foo')
    def handle_foo(self, *events):
        print('foo was set to', events[-1].new_value)

    @event.connect('bar')
    def on_bar(self, *events):
        for ev in events:
            print('bar event was generated')

ob = MyObject(foo=42)

@ob.connect('foo')
def another_foo handler(*events):
    print('foo was set %i times' % len(events))
_init_handlers()

Initialize handlers and properties. You should only do this once, and only when using the object is initialized with init_handlers=False.

_set_prop(prop_name, value, _initial=False)

Set the value of a (readonly) property.

Parameters:
  • prop_name (str) – the name of the property to set.
  • value – the value to set.
connect(*connection_strings)

Connect a function to one or more events of this instance. Can also be used as a decorator. See the connect decorator for more information.

h = HasEvents()

# Usage as a decorator
@h.connect('first_name', 'last_name')
def greet(*events):
    print('hello %s %s' % (h.first_name, h.last_name))

# Direct usage
h.connect(greet, 'first_name', 'last_name')

# Order does not matter
h.connect('first_name', greet)
disconnect(type, handler=None)

Disconnect handlers.

Parameters:
  • type (str) – the type for which to disconnect any handlers. Can include the label to only disconnect handlers that were registered with that label.
  • handler (optional) – the handler object to disconnect. If given, only this handler is removed.
dispose()

Use this to dispose of the object to prevent memory leaks.

Make all subscribed handlers to forget about this object, clear all references to subscribed handlers, disconnect all handlers defined on this object.

emit(type, info=None)

Generate a new event and dispatch to all event handlers.

Parameters:
  • type (str) – the type of the event. Should not include a label.
  • info (dict) – Optional. Additional information to attach to the event object. Note that the actual event is a Dict object that allows its elements to be accesses as attributes.
get_event_handlers(type)

Get a list of handlers for the given event type. The order is the order in which events are handled: alphabetically by label.

Parameters:type (str) – the type of event to get handlers for. Should not include a label.
get_event_types()

Get the known event types for this HasEvent object. Returns a list of event type names, for which there is a property/emitter or for which any handlers are registered. Sorted alphabetically.

Handler

class flexx.event.Handler(func, connection_strings, ob)

Wrapper around a function object to connect it to one or more events. This class should not be instantiated directly; use event.connect or HasEvents.connect instead.

Parameters:
  • func (callable) – function that handles the events.
  • connection_strings (list) – the strings that represent the connections.
  • ob (HasEvents) – the HasEvents object to use a a basis for the connection. A weak reference to this object is stored.
dispose()

Cleanup any references.

Disconnects all connections, and cancel all pending events.

get_connection_info()

Get a list of tuples (name, connection_names), where connection_names is a list of type names (including label) for the made connections.

get_name()

Get the name of this handler, usually corresponding to the name of the function that this handler wraps.

handle_now()

Invoke a call to the handler function with all pending events. This is normally called in a next event loop iteration when an event is scheduled for this handler, but it can also be called manually to force the handler to process pending events now.

Dict

class flexx.event.Dict

A dict in which the items can be get/set as attributes.

This provides a lean way to represent structured data, and works well in combination with autocompletion. Keys can be anything that are otherwise valid keys, but keys that are not valid identifiers or that are methods of the dict class (e.g. ‘items’ or ‘copy’) can only be get/set in the classic way.

Example:

>> d = Dict(foo=3)
>> d.foo
3
>> d['foo'] = 4
>> d.foo
4
>> d.bar = 5
>> d.bar
5

loop

class flexx.event._loop.Loop

A simple proxy event loop. There is one instance in flexx.event.loop. This is used by handlers to register the handling of pending events. Users typically don’t need to be aware of this.

This proxy can integrate with an existing event loop (e.g. of Qt and Tornado). If Qt or Tornado is imported at the time that flexx.event gets imported, the loop is integrated automatically. This object can also be used as a context manager; events get processed when the context exits.

call_later(func)

Call the given function in the next iteration of the event loop.

integrate(call_later_func=None, raise_on_fail=True)

Integrate with an existing event loop system.

Params:
call_later_func (func): a function that can be called to
schedule the calling of a given function. If not given, will try to connect to Tornado or Qt event loop, but only if either library is already imported.
raise_on_fail (bool): whether to raise an error when the
integration could not be performed.
integrate_pyqt4()

Integrate with PyQt4.

integrate_pyside()

Integrate with PySide.

integrate_tornado()

Integrate with tornado.

iter()

Do one event loop iteration; process all pending function calls.