This example shows how to define a listener for a property set event. The listener callback triggers when the value of a specific property changes. The class defined for this example uses a method for a push-button callback and a static method for the listener callback. When the push-button callback changes the value of a property, the listener executes its callback on the PreSet
event.
This example defines a class (PushButton
) with these design elements:
ResultNumber
– Observable property
uicontrol pushbutton
– Push-button object used to generate a new graph when its callback executes
A listener that responds to a change in the observable property
The PushButton
class creates figure
, uicontrol
, axes
graphics objects, and a listener object in the class constructor.
The push button's callback is a class method (named pressed
). When the push button is activated, the following sequence occurs:
MATLAB® executes the pressed
method, which graphs a new set of data and increments the ResultNumber
property.
Attempting to set the value of the ResultNumber
property triggers the PreSet
event, which executes the listener callback before setting the property value.
The listener callback uses the event data to obtain the handle of the callback object (an instance of the PushButton
class), which then provides the handle of the axes object that is stored in its AxHandle
property.
The listener callback updates the axes Title
property, after the callback completes execution, MATLAB sets the ResultsNumber
property to its new value.
classdef PushButton < handle properties (SetObservable) ResultNumber = 1 end properties AxHandle end methods function buttonObj = PushButton myFig = figure; buttonObj.AxHandle = axes('Parent',myFig); uicontrol('Parent',myFig,... 'Style','pushbutton',... 'String','Plot Data',... 'Callback',@(src,evnt)pressed(buttonObj)); addlistener(buttonObj,'ResultNumber','PreSet',... @PushButton.updateTitle); end end methods function pressed(obj) scatter(obj.AxHandle,randn(1,20),randn(1,20),'p') obj.ResultNumber = obj.ResultNumber + 1; end end methods (Static) function updateTitle(~,eventData) h = eventData.AffectedObject; set(get(h.AxHandle,'Title'),'String',['Result Number: ',... num2str(h.ResultNumber)]) end end end
The scatter graph looks similar to this graph after three push-button clicks.
buttonObj = PushButton;