Matlab Events and Listeners

Specifying Events

To define an event, you declare a name for the event in the events block. Then one of the class methods triggers the event using the notify method, which is method inherited from the handle class. Only classes derived from the handle class can define events.

For example, the following class:

  • Defines an event named StateChange
  • Triggers the event using the inherited notify method.
  • classdef class_name < handle % Subclass handle
       events % Define an event called StateChange
          StateChange
       end
       ...
       methods
          function upDateGUI(obj)
             ...
             % Broadcast notice that StateChange event has occurred
             notify(obj,'StateChange');
          end
       end
    end

    Listening for Events

Any number of objects can be listening for the StateChange event to occur. When notify executes, MATLAB calls all registered listener callbacks and passes the handle of the object generating the event and an event structure to these functions. To register a listener callback, use the addlistener method of the handle class.

addlistener(event_obj,'StateChange',@myCallback)

[important]See Defining Events and Listeners — Syntax and Techniques[/important]

You may also like...