MATLAB Object-Oriented Programming

(Joyce) #1

  • @RespondToToggle.handleEvnt — A function handle to the callback function (see
    the following definition “Define Listener” on page 11-24).


Use handle.listener to Decouple Listener and Source

Use the handle.listener method to create listeners when you want to manage the
lifecycle of the listener and do not want a coupling between the event source and listener
object. MATLAB does not destroy listeners created with handle.listener when the
event source is destroyed. However, your code must keep the listener object handle in
scope when creating listeners using handle.listener.

The handle.listener method requires the same arguments as handle.addlistener:
the event-naming object, the event name, and a function handle to the callback.
handle.listener returns the handle to the listener object.

lh = listener(obj,'EventName',@callbackFunction)

For example, this code uses the ToggleState event discussed previously:

lh = listener(obj,'ToggleState',@RespondToToggle.handleEvnt)

Callback Function

The listener callback function must accept a minimum of two arguments, which MATLAB
automatically passes to the callback. Here are the required arguments:


  • The source of the event — that is, obj in the call to addlistener or
    event.listener.

  • An event.EventData object or a subclass of event.EventData, such as the
    ToggleEventData object described in, “Define Event-Specific Data” on page 11-26.


Define the callback function to accept the source object and event data arguments.

function callbackFunction(src,evtdata)
...
end

For more information on callback syntax, see “Listener Callback Syntax” on page 11-30.

Define Listener

The RespondToToggle class defines objects that listen for the ToggleState event
defined in the ToggleButton class.

11 Events — Sending and Responding to Messages

Free download pdf