Main Content

Events and Listeners Syntax

Components to Implement

Implementation of events and listeners involves these components:

  • Specification of the name of an event in a handle class — Name Events.

  • A function or method to trigger the event when the action occurs — Trigger Events.

  • Listener objects to execute callback functions in response to the triggered event — Listen to Events.

  • Default or custom event data that the event passes to the callback functions — Define Event-Specific Data.

Name Events

Define an event by declaring an event name inside an events block. For example, this class creates an event called ToggleState:

classdef ToggleButton < handle
   properties
      State = false
   end
   events
      ToggleState
   end
end

Events cannot have the same name as the class that defines them.

Trigger Events

The OnStateChange method calls notify to trigger the ToggleState event. Pass the handle of the object that is the source of the event and the name of the event to notify.

classdef ToggleButton < handle
   properties
      State = false
   end
   events
      ToggleState
   end
   methods
      function OnStateChange(obj,newState)
         if newState ~= obj.State
            obj.State = newState;
            notify(obj,'ToggleState');
         end
      end
   end
end

Listen to Events

After the call to notify triggers an event, MATLAB® broadcasts a message to all listeners that are defined for that event and source object. There are two ways to create listeners: using the handle class addlistener or listener method.

Use addlistener for Persistent Listeners

If you want the listener to persist beyond the normal variable scope, use addlistener to create it. The event source object holds a reference to the listener object. When the event source object is destroyed, MATLAB destroys the listener.

This code defines a listener for the ToggleState event:

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

addlistener has these arguments:

  • obj — The object that is the source of the event

  • ToggleState — The event name passed as a char vector

  • @RespondToToggle.handleEvnt — A function handle to the callback function (see the following definition Define Listener).

Use handle.listener to Decouple Listener and Source

Use the 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 listener when the event source is destroyed. However, your code must keep the listener object handle in scope when creating listeners using listener.

The listener method requires the same arguments as addlistener: the event-naming object, the event name, and a function handle to the callback. 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.

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.

Define Listener

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

classdef RespondToToggle < handle
   methods
      function obj = RespondToToggle(toggle_button_obj)
         addlistener(toggle_button_obj,'ToggleState',@RespondToToggle.handleEvnt);
      end
   end
   methods (Static)
      function handleEvnt(src,~)
         if src.State
            disp('ToggleState is true')
         else
            disp('ToggleState is false')
         end
      end
   end
end

The class RespondToToggle adds the listener in its constructor. In this case, the class defines the callback (handleEvnt) as a static method that accepts the two required arguments:

  • src — The handle of the object triggering the event (that is, a ToggleButton object)

  • evtdata — An event.EventData object

For example, this code creates objects of both classes:

tb = ToggleButton;
rtt = RespondToToggle(tb);

Whenever you call the OnStateChange method of the ToggleButton object, notify triggers the event. For this example, the callback displays the value of the State property:

tb.OnStateChange(true)
ToggleState is true
tb.OnStateChange(false)
ToggleState is false

Remove Listeners

Remove a listener object by calling delete on its handle. For example, if the class RespondToToggle saved the listener handle as a property, you could delete the listener.

classdef RespondToToggle < handle
   properties
      ListenerHandle % Property for listener handle
   end
   methods
      function obj = RespondToToggle(toggle_button_obj)
         hl = addlistener(toggle_button_obj,'ToggleState',@RespondToToggle.handleEvnt);
         obj.ListenerHandle = hl; % Save listener handle
      end
   end
   methods (Static)
      function handleEvnt(src,~)
         if src.State
            disp('ToggleState is true')
         else
            disp('ToggleState is false')
         end
      end
   end
end

With this code change, you can remove the listener from an instance of the RespondToToggle class. For example:

tb = ToggleButton;
rtt = RespondToToggle(tb); 

The object rtt is listening for the ToggleState event triggered by object tb. To remove the listener, call delete on the property containing the listener handle.

delete(rtt.ListenerHandle)

To deactivate a listener temporarily, see Temporarily Deactivate Listeners.

Define Event-Specific Data

Suppose that you want to pass the state of the toggle button as a result of the event to the listener callback. You can add more data to the default event data by subclassing the event.EventData class and adding a property to contain this information. Then you can pass this object to the notify method.

Note

To save and load objects that are subclasses of event.EventData, such as ToggleEventData, enable the ConstructOnLoad class attribute for the subclass.

classdef (ConstructOnLoad) ToggleEventData < event.EventData
   properties
      NewState
   end
   
   methods
      function data = ToggleEventData(newState)
         data.NewState = newState;
      end
   end
end

The call to notify can use the ToggleEventData constructor to create the necessary argument.

evtdata = ToggleEventData(newState);
notify(obj,'ToggleState',evtdata);

Related Topics