Events and Listeners

Define and Trigger Events

To define an event, declare a name for the event in an events block. Trigger the event using the handle class notify method. Only classes derived from the handle class can define events.

For example, MyClass class:

  • Subclasses handle

  • Defines an event named StateChange

  • Triggers the event using the inherited notify method in its upDateUI method.

classdef MyClass < handle 
   events 
      StateChange
   end
   ...
   methods
      function upDateUI(obj)
         ...
         notify(obj,'StateChange');
      end
   end
end

Listen for Events

Any number of objects can listen to the StateChange event. When notify executes, MATLAB® calls all registered listener callbacks. MATLAB passes the handle of the object generating the event and event data to the callback functions. To create a listener, use the addlistener method of the handle class.

addlistener(event_obj,'StateChange',@myCallback)

To control the lifecycle of the listener, use the event.listener constructor to create the listener object.

See Also

| |

Related Topics