Documentation

Learn to Use Events and Listeners

Why Use Events and Listeners

Events are notices that objects broadcast in response to something that happens, such as a property value changing or a user interaction with an application program. Listeners execute functions when notified that the event of interest occurs. Use events to communicate things that happen to objects, and respond to these events by executing the listener's callback function.

See Events and Listeners — Concepts for a more thorough discussion of the MATLAB® event model.

Events and Listeners Basics

When using events and listeners:

  • Only handle classes can define events and listeners.

  • Call the handle notify method to trigger the event. The event notification broadcasts the named event to all listeners registered for this event.

  • Use the handle addlistener method to associate a listener with an object that will be the source of the event.

  • When adding a listener, pass a function handle for the listener callback function using a syntax such as the following:

    • addlistener(eventObject,'EventName',@functionName) — for an ordinary function.

    • addlistener(eventObject,'EventName',@Obj.methodName) — for a method of Obj.

    • addlistener(eventObject,'EventName',@ClassName.methodName) — for a static method of the class ClassName.

  • Listener callback functions must define at least two input arguments — the event source object handle and the event data (See Function Handle for Listener Callbacks for more information).

  • You can modify the data passed to each listener callback by subclassing the event.EventData class.

Events and Listeners Syntax Overview

Define an event name in the events code block:

classdef ClassName < handle
   ...
   events
      EventName
   end
   ...
end

For example, MyClass defines an event named StateChange:

classdef MyClass < handle
   events
      StateChange
   end
end

Trigger an event using the handle class notify method:

classdef ClassName < handle
   ...
   events
      EventName
   end
   ...
   methods
      function anyMethod(obj)
         ...
         notify(obj,'EventName');
      end
end

Any function or method can trigger the event for a specific instance of the class defining the event. For example, the triggerEvent method calls notify to trigger the StateChange event:

classdef MyClass < handle
   events
      StateChange
   end
   methods
      function triggerEvent(obj)
         notify(obj,'StateChange')
      end
   end
end

Trigger the StateChange event with the triggerEvent method:

obj = MyClass;
obj.triggerEvent

Define a listener using the handle class addlistener method:

ListenerObject = addlistener(SourceOfEvent,'EventName',@listenerCallback);

addlistener returns the listener object. The input arguments are:

  • SourceOfEvent — An object of the class defining the event on which the event occurred.

  • EventName — The name of the event defined in the class events code block.

  • @listenerCallback — a function handle referencing the function that executes in response to the event.

For example, create a listener object for the StateChange event:

function lh = createListener(src)
   lh = addlistener(src,'StateChange',@handleStateChange)
end

Define the callback function for the listener. The callback function must accept as the first two arguments the event source object and an event data object:

function handleStateChange(src,eventData)
   ...
end

Class with Custom Event Data

Suppose you want to create a listener callback function that has access to specific information when the event occurs. This example shows how to do this by creating custom event data.

Events provide information to listener callback functions by passing an event data argument to the specified function. By default, MATLAB passes an event.EventData object to the listener callback. This object has two properties:

  • EventName — Name of the event triggered by this object.

  • Source — Handle of the object triggering the event.

Provide additional information to the listener callback by subclassing the event.EventData class.

  • Define properties in the subclass to contain the additional data.

  • Define a constructor that accepts the additional data as arguments.

  • Set the ConstructOnLoad class attribute.

  • Use the subclass constructor as an argument to the notify method to trigger the event.

Defining and Triggering an Event

The SimpleEventClass defines a property set method (see Property Set Methods) from which it triggers an event if the property is set to a value exceeding a certain limit. The property set method performs these operations:

  • Saves the original property value

  • Sets the property to the specified value

  • If the specified value is greater than 10, the set method triggers an Overflow event

  • Passes the original property value, as well as other event data, in a SpecialEventDataClass object to the notify method.

classdef SimpleEventClass < handle
   properties
      Prop1 = 0;
   end
   events
      Overflow
   end
   methods
      function set.Prop1(obj,value)
         orgvalue = obj.Prop1;
         obj.Prop1 = value;
         if (obj.Prop1 > 10)
            % Trigger the event using custom event data
            notify(obj,'Overflow',SpecialEventDataClass(orgvalue));
         end
      end
   end
end

Define the Event Data

Event data is always contained in an event.EventData object. The SpecialEventDataClass adds the original property value to the event data by subclassing event.EventData:

classdef (ConstructOnLoad) SpecialEventDataClass < event.EventData
   properties
      OrgValue = 0;
   end
   methods
      function eventData = SpecialEventDataClass(value)
         eventData.OrgValue = value;
      end
   end
end

Create a Listener for the Overflow Event

To listen for the Overflow event, attach a listener to an instance of the SimpleEventClass class. Use the addlistener method to create the listener. You also need to define a callback function for the listener to execute when the event is triggered.

The function setupSEC instantiates the SimpleEventClass class and adds a listener to the object. In this example, the listener callback function displays information that is contained in the eventData argument (which is a SpecialEventDataClass object).

function sec = setupSEC
   sec = SimpleEventClass;
   addlistener(sec,'Overflow',@overflowHandler)
   function overflowHandler(eventSrc,eventData)
      disp('The value of Prop1 is overflowing!')
      disp(['Its value was: ' num2str(eventData.OrgValue)])
      disp(['Its current value is: ' num2str(eventSrc.Prop1)])
   end
end

Create the SimpleEventClass object and add the listener:

sec = setupSEC;
sec.Prop1 = 5;
sec.Prop1 = 15; % listener triggers callback
The value of Prop1 is overflowing!
Its value was: 5
Its current value is: 15

Class to Observe Property Changes

This example shows how to listen for changes to a property value. This examples uses:

  • PostSet event predefined by MATLAB

  • SetObservable property attribute to enable triggering the property PostSet event.

  • addlistener handle class method to create the listener

classdef PropLis < handle
   % Define a property that is SetObservable
   properties (SetObservable)
      ObservedProp = 1;
   end
   methods
      function attachListener(obj)
         %Attach a listener to a PropListener object
         addlistener(obj,'ObservedProp','PostSet',@PropLis.propChange);
      end
   end
   methods (Static)
      function propChange(metaProp,eventData)
         % Callback for PostSet event
         % Inputs: meta.property object, event.PropertyEvent
         h = eventData.AffectedObject;
         propName = metaProp.Name;
         disp(['The ',propName,' property has changed.'])
         disp(['The new value is: ',num2str(h.ObservedProp)])
         disp(['Its default value is: ',num2str(metaProp.DefaultValue)])
      end
   end
end

The PropLis class uses an ordinary method (attachListener) to add the listener for the ObservedProp property. If the PropLis class defines a constructor, the constructor can contain the call to addlistener.

The listener callback is a static method (propChange). MATLAB passes two arguments when calling this function:

These arguments provide information about the property and the event.

Use the PropLis class by creating an instance and calling its attachListener method:

plObj = PropLis;
plObj.ObservedProp
ans =

     1
plObj.attachListener
plObj.ObservedProp = 2;
The ObservedProp property has changed.
The new value is: 2
Its default value is: 1

Related Examples

Was this topic helpful?