Example — Using Events to Update Graphs

Example Overview

This example defines two classes:

This class defines two events:

The following diagram shows the relationship between the two objects. The fcnview object contains a fcneval object and creates graphs from the data it contains. fcnview creates listeners to change the graphs if any of the data in the fcneval object change.

Access Fully Commented Example Code

You can display the code for this example in a popup window that contains detailed comments and links to related sections of the documentation by clicking these links:

fcneval class

fcnview class

createViews static method

You can open all files in your editor by clicking this link:

Open in editor

To use the classes, save the files in directories with the following names:

The @-directory's parent directory must be on the MATLAB path.

Techniques Demonstrated in This Example

Summary of fcneval Class

The fcneval class is designed to evaluate a MATLAB expression over a specified range of two variables. It is the source of the data that is graphed as a surface by instances of the fcnview class. It is the source of the events used in this example.

PropertyValuePurpose
FofXYfunction handleMATLAB expression (function of two variables).
Lmtwo-element vectorLimits over which function is evaluated in both variables. SetObservable attribute set to true to enable property event listeners.
Datastructure with x, y, and z matricesData resulting from evaluating the function. Used for surface graph. Dependent attribute set to true, which means the get.Data method is called to determine property value when queried and no data is stored.

EventWhen Triggered
UpdateGraphFofXY property set function (set.FofXY) calls the notify method when a new value is specified for the MATLAB expression on an object of this class.

MethodPurpose
fcnevalClass constructor. Inputs are function handle and two-element vector specifying the limits over which to evaluate the function.
set.FofXYFofXY property set function. Called whenever property value is set, including during object construction.
set.LmLm property set function. Used to test for valid limits.
get.DataData property get function. This method calculates the values for the Data property whenever that data is queried (by class members or externally).
gridA static method (Static attribute set to true) used in the calculation of the data.

Summary of fcnview Class

Instances of the fcnview class contain fcneval objects as the source of data for the four surface graphs created in a function view. fcnview creates the listeners and callback functions that respond to changes in the data contained in fcneval objects.

PropertyValuePurpose
FcnObjectfcneval objectThis object contains the data that is used to create the function graphs.
HAxesaxes handleEach instance of a fcnview object stores the handle of the axes containing its subplot.
HLUpdateGraphevent.listener object for UpdateGraph eventSetting the event.listener object's Enabled property to true enables the listener; false disables listener.
HLLmevent.listener object for Lm property eventSetting the event.listener object's Enabled property to true enables the listener, false disables listener.
HEnableCmuimenu handleItem on context menu used to enable listeners (used to handle checked behavior)
HDisableCmuimenu handleItem on context menu used to disable listeners (used to manage checked behavior)
HSurfacesurface handleUsed by event callbacks to update surface data.

MethodPurpose
fcnviewClass constructor. Input is fcneval object.
createLisnCalls addlistener to create listeners for UpdateGraph and Lm property PostSet listeners.
limsSets axes limits to current value of fcneval object's Lm property. Used by event handlers.
updateSurfaceDataUpdates the surface data without creating a new object. Used by event handlers.
listenUpdateGraphCallback for UpdateGraph event.
listenLmCallback for Lm property PostSet event
deleteDelete method for fcnview class.
createViewsStatic method that creates an instance of the fcnview class for each subplot, defines the context menus that enable/disable listeners, and creates the subplots

Methods Inherited from Handle Class

Both the fcneval and fcnview classes inherit methods from the handle class. The following table lists only those inherited methods used in this example.

Handle Class Methods provides a complete list of methods that are inherited when you subclass the handle class.

Methods Inherited from Handle ClassPurpose
addlistenerRegister a listener for a specific event and attach listener to event-defining object.
notifyTrigger an event and notify all registered listeners.

Using the fcneval and fcnview Classes

This sections explains how to use the classes.

You create a fcneval object by calling its constructor with two arguments—an anonymous function and a two-element, monotonically increasing vector. For example:

feobject = fcneval(@(x,y) x.*exp(-x.^2-y.^2),[-2 2]);

Use the createViews static method to create the graphs of the function. Note that you must use the class name to call a static function:

fcnview.createViews(feobject);

The createView method generates four views of the function contained in the fcneval object.

Each subplot defines a context menu that can enable and disable the listeners associated with that graph. For example, if you disable the listeners on subplot 221 (upper left) and change the MATLAB expression contained by the fcneval object, only the remaining three subplots update when the UpdateGraph event is triggered:

feobject.FofXY = @(x,y) x.*exp(-x.^.5-y.^.5);

Similarly, if you change the limits by assigning a value to the feobject.Lm property, the feobject triggers a PostSet property event and the listener callbacks update the graph.

feobject.Lm = [-8 3];

In this figure the listeners are re-enabled via the context menu for subplot 221. Because the listener callback for the property PostSet event also updates the surface data, all views are now synchronized

Implementing the UpdateGraph Event and Listener

The UpdateGraph event occurs when the MATLAB representation of the mathematical function contained in the fcneval object is changed. The fcnview objects that contain the surface graphs are listening for this event, so they can update the graphs to represent the new function.

Defining and Firing the UpdateGraph Event

The UpdateGraph event is a class-defined event. The fcneval class names the event and calls notify when the event occurs.

The fcnview class defines a listener for this event. When fcneval triggers the event, the fcnview listener executes a callback function that performs the follow actions:

The fcneval class defines an event name in an event block:

events
   UpdateGraph 
end

It is the responsibility of the class to explicitly trigger the event by calling the notify method. In this example, notify is called from the set function of the property that stores the MATLAB expression for the mathematical function:

function fofxy = set.FofXY(obj,func)
   obj.FofXY = func; % Assign property value
   notify(obj,'UpdateGraph'); % Trigger UpdateGraph event
end 

The class could have implemented a property event for the FofXY property and would, therefore, not need to call notify. Defining a class event provides more flexibility in controlling when the event is triggered.

Defining the Listener and Callback for the UpdateGraph Event

The fcnview class creates a listener for the UpdateGraph event using the addlistener method:

obj.HLUpdateGraph = addlistener(obj.FcnObject,'UpdateGraph',...
            @(src,evnt)listenUpdateGraph(obj,src,evnt)); % Add obj to argument list

The fcnview object stores a handle to the event.listener object in its HLUpdateGraph property, which is used to enable/disable the listener by a context menu (see Enabling and Disabling the Listeners).

The fcnview object (obj) is added to the two default arguments (src, evnt) passed to the listener callback. Keep in mind, the source of the event (src) is the fcneval object, but the fcnview object contains the handle of the surface object that is updated by the callback.

The listenUpdateGraph function is defined as follows:

function listenUpdateGraph(obj,src,evnt)
   if ishandle(obj.HSurface) % If surface exists
      obj.updateSurfaceData % Update surface data
   end
end

The updateSurfaceData function is a class method that updates the surface data when a different mathematical function is assigned to the fcneval object. Updating a graphics object data is generally more efficient than creating a new object using the new data:

function updateSurfaceData(obj)
% Get data from fcneval object and set surface data
   set(obj.HSurface,...
      'XData',obj.FcnObject.Data.X,...
      'YData',obj.FcnObject.Data.Y,...
      'ZData',obj.FcnObject.Data.Matrix); 
end

Implementing the PostSet Property Event and Listener

All properties support the predefined PostSet event (See Property-Set and Query Events for more information on property events). This example uses the PostSet event for the fcneval Lm property. This property contains a two-element vector specifying the range over which the mathematical function is evaluated. Just after this property is changed (by a statement like obj.Lm = [-3 5];), the fcnview objects listening for this event update the graph to reflect the new data.

Sequence During the Lm Property Assignment

The fcneval class defines a set function for the Lm property. When a value is assigned to this property during object construction or property reassignment, the following sequence occurs:

  1. An attempt is made to assign argument value to Lm property.

  2. The set.Lm method executes to check whether the value is in appropriate range — if yes, it makes assignment, if no, it generates an error.

  3. If the value of Lm is set successfully, the MATLAB runtime triggers a PostSet event.

  4. All listeners execute their callbacks, but the order is nondeterministic.

The PostSet event does not occur until an actual assignment of the property occurs. The property set function provides an opportunity to deal with potential assignment errors before the PostSet event occurs.

Enabling the PostSet Property Event

To create a listener for the PostSet event, you must set the property's SetObservable attribute to true:

properties (SetObservable = true)
   Lm = [-2*pi 2*pi];  % specifies default value
end 

The MATLAB runtime automatically triggers the event so it is not necessary to call notify.

Specifying Property Attributes provides a list of all property attributes.

Defining the Listener and Callback for the PostSet Event

The fcnview class creates a listener for the PostSet event using the addlistener method:

obj.HLLm = addlistener(obj.FcnObject,'Lm','PostSet',...
            @(src,evnt)listenLm(obj,src,evnt)); % Add obj to argument list

The fcnview object stores a handle to the event.listener object in its HLLm property, which is used to enable/disable the listener by a context menu (see Enabling and Disabling the Listeners).

The fcnview object (obj) is added to the two default arguments (src, evnt) passed to the listener callback. Keep in mind, the source of the event (src) is the fcneval object, but the fcnview object contains the handle of the surface object that is updated by the callback.

The callback sets the axes limits and updates the surface data because changing the limits causes the mathematical function to be evaluated over a different range:

function listenLm(obj,src,evnt)
   if ishandle(obj.HAxes) % If there is an axes
      lims(obj); % Update its limits
      if ishandle(obj.HSurface) % If there is a surface
         obj.updateSurfaceData % Update its data
      end
   end
end 

Enabling and Disabling the Listeners

Each fcnview object stores the handle of the listener objects it creates so that the listeners can be enabled or disabled via a context menu after the graphs are created. All listeners are instances of the event.listener class, which defines a property called Enabled. By default, this property has a value of true, which enables the listener. If you set this property to false, the listener still exists, but is disabled. This example creates a context menu active on the axes of each graph that provides a way to change the value of the Enabled property.

Context Menu Callback

There are two callbacks used by the context menu corresponding to the two items on the menu:

Both callbacks include the fcnview object as an argument (in addition to the required source and event data arguments) to provide access to the handle of the listener objects.

The enableLisn function is called when the user selects Listen from the context menu.

function enableLisn(obj,src,evnt)
   obj.HLUpdateGraph.Enabled = true; % Enable listener
   obj.HLLm.Enabled = true; % Enable listener
   set(obj.HEnableCm,'Checked','on') % Check Listen
   set(obj.HDisableCm,'Checked','off') % Uncheck Don't Listen
end

The disableLisn function is called when the user selects Don't Listen from the context menu.

function disableLisn(obj,src,evnt)
   obj.HLUpdateGraph.Enabled = false; % Disable listener
   obj.HLLm.Enabled = false; % Disable listener
   set(obj.HEnableCm,'Checked','off') % Unheck Listen
   set(obj.HDisableCm,'Checked','on') % Check Don't Listen
end
  


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