Products & Services Industries Academia Support User Community Company

Learn more about MATLAB   

Learning to Use Events and Listeners

What You Can Do With 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 notification of the event of interest occurs. You can use events to communicate things that happen in your program to other objects, which then can 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.

Some Basic Examples

The following sections provide simple examples that show the basic techniques for using events and listeners. Subsequent sections provide more detailed descriptions and more complex examples.

Quick Overview

When using events and listeners:

Simple Event Listener Example

Suppose you want to create a listener callback 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:

You can provide additional information to the listener callback by subclassing the event.EventData class. In your subclass, you define properties to contain the additional data and provide a constructor method that accepts the additional data as arguments. Typically, you use the subclass constructor as an argument to the notify method, which is the method that you use to trigger the event.

See Defining Event-Specific Data for another example of subclassing event.EventData.

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:

classdef SimpleEventClass < handle
% Must be a subclass of 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

Defining 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 SpecialEventDataClass < event.EventData
   properties
      OrgValue = 0;
   end
   methods
      function eventData = SpecialEventDataClass(value)
            eventData.OrgValue = value;
      end
   end
end

Creating 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
   % Create an object and attach the listener
   sec = SimpleEventClass;
   addlistener(sec,'Overflow',@overflowHandler)
   % Define the listener callback function
   function overflowHandler(eventSrc,eventData)
      disp('The value of Prop1 is overflowing!')
      disp(['It''s value was: ' num2str(eventData.OrgValue)])
      disp(['It''s current value is: ' num2str(eventSrc.Prop1)])
   end
end

Responding to a Push Button

This example shows how to respond to changes in the state of a push button by listening for changes in the value of a property. It uses the predefined property set events (see Listening for Changes to Property Values for more on property events). The example defines the following components:

The PushButton Class

The PushButton class uses a uicontrol to create a push button. The push button's callback function is a class method (which requires the object to reference it, buttonObj.pressed) that changes the value of the class's State property, which generates a property set event because the property's SetObservable attribute is enabled:

classdef PushButton < handle
% must be a subclass of handle
   properties (SetObservable)
   % Enable property events with SetObservable attribute
      State = false;
   end
   methods
      function buttonObj = PushButton
         uicontrol('Style','pushbutton',...
            'String','R/B',...
            'Callback',@buttonObj.pressed);
      end
   end
   methods (Access = private)
   % Make push button callback private
      function pressed(buttonObj,src,event) % #ok<INUSD>
      % Setting value of State property triggers property set events
         buttonObj.State = ~buttonObj.State;
      end
   end
end

The AxesObj Class

The AxesObj class contains an axes object that is displayed in the figure window containing the push button. Its Grid property contains a logical value that determines whether to display the grid.

The private PrivGrid property isolates the Grid property from load order dependencies if the object is loaded from a MAT-file. See Avoiding Property Initialization Order Dependency for more information.

classdef AxesObj < handle
   properties (Access = private)
   % Keep the axes handle private
      MyAxes = axes;
      PrivGrid = true;
   end
   properties (Dependent)
   % Determines if the grid is on or off
      Grid = false;
   end
   methods
      function set.Grid(axObj,newGrid)
      % Set method for Grid property
      % As push button State changes,
      % listener sets AxesObj Grid property
            axObj.PrivGrid = newGrid;
            if axObj.Grid
                grid(axObj.MyAxes,'on');
            else
                grid(axObj.MyAxes,'off');
         end
      end
      function g = get.Grid(axObj)
         g = axObj.PrivGrid;
      end
   end
end

Creating a Listener for the Property Event

The listener is the connection between the push button and the axes. The listener responds to the event that is triggered when the push button is clicked by executing its callback function. This function changes the display of the grid according to the state of the push button. The listener responds to the property PostSet event, which means the listener callback executes after the property has been set.

function setup
   pb = PushButton;
   axo = AxesObj;
   % listener responds to the PostSet event triggered after
   % the PushButton State property changes value
   addlistener(pb,'State','PostSet',@mapper);
   function mapper(src,event) % #ok<INUSD>
      axo.Grid = pb.State;
   end   
end
  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2009- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS