- Undocumented Matlab - https://undocumentedmatlab.com -

Property value change listeners

Posted By Yair Altman On August 13, 2014 | 14 Comments

For performance reasons, it is almost always better to respond to events (asynchronously), than to continuously check a property value (synchronous polling). Therefore, if we wish to do something when some property value is changed (e.g., log the event, shut down the system, liquidate the portfolio, call the police, …), then it is preferable to attach a property-change listener callback.
The standard (documented) way of attaching a value-change listener to Matlab class properties is via the addlistener [1] function. This only works for handle (not value) classes, and only to those properties that have the SetObservable and/or GetObservable attribute turned on [2]:

addlistener(hClassObject, propertyName, 'PostSet', @myCallbackFcn);

This is all nice and well for Matlab class properties, but what about HG (handle Graphics: plots & GUI) properties? Can we similarly listen to changes in (say) the axes limits? Until now this has been possible, but undocumented. For example, this will trigger myCallbackFcn(hAxes,eventData) whenever the axes limits change (due to zoom, pan, plotting etc.):

addlistener(gca, 'YLim', 'PostSet', @(hAxes,eventData) myCallbackFcn(hAxes,eventData));
% Or (shorter equivalent):
addlistener(gca, 'YLim', 'PostSet', @myCallbackFcn);

This could be very useful when such properties could be modified from numerous different locations. Rather than updating all these location to call the relevant callback function directly, we simply attach the callback to the property-change listener. It could also be useful in cases where for some reason we cannot modify the source of the update (e.g., third-party or legacy code).
In addition to PostSet, we could also set listeners for PreSet. Also, we could set listeners on PostGet and PreGet – this could be useful for calculating dynamic (dependent) property values.

Under the hood

The HG1 variant of addlistener is basically equivalent to the following low-level UDD-based code snippet, as explained here [3]:

% Create the listener object
hAxes = handle(gca);  % a UDD axes class object
hProp = findprop(hAxes,'YLim');  % a schema.prop class object
hListener = handle.listener(hAxes, hProp, 'PropertyPostSet', @myCallbackFcn);
% persist the listener in memory for as long as the source object (hAxes) is alive
setappdata(hAxes, 'listener__', hListener);

(in old Matlab releases, addlistener was a regular m-function that placed the listeners in the source handle’s ApplicationData property, as the code above shows; newer releases reimplemented addlistener as an internal built-in function and the listener is now stored somewhere in the DLL’s inaccessible memory, rather than in the ApplicationData property)
In HG2, handle.listener no longer works. Fortunately, we don’t need it since we have addlistener that works the same way for both HG1 (UDD objects) and HG2 (MCOS objects). Kudos on the backward-compatibility aspect, MathWorks!

Categories: GUI, Handle graphics, Listeners, Low risk of breaking in future versions, Stock Matlab function, Undocumented feature

14 Comments (Open | Close)

14 Comments To "Property value change listeners"

#1 Comment By David On September 2, 2014 @ 12:55

You can also call the event.proplistener constructor directly instead of using add listener which creates a listener not tied to the lifecycle of the object being listened to.


#2 Comment By Yair Altman On September 2, 2014 @ 13:01

@David – I think you have it backwards: event.proplistener creates a standalone listener that is not tied to the object’s lifecycle. This means that it works only as long as the listener variable is in memory (not cleared). In order to persist it to live as long as the object, the typical use would be to store this listener in the object’s UserData or ApplicationData properties.

On the other hand, addlistener already does all this for us. It is therefore both easier and safer to use.

#3 Comment By David On September 2, 2014 @ 13:33

Hi Yair,

Maybe there should have been a comma or two in my original statement to avoid confusion as we are definitely both talking about the same thing. Typical usage (assuming we are all using OOP) would be to store the event.listener/event.proplistener as a property in the class where it was created. In my applications I almost always use event.listener and event.proplistener as advised by MathWorks.

“You can also call the event.proplistener constructor directly, instead of using addlistener, which creates a listener not tied to the lifecycle of the object being listened to.”

#4 Comment By David On September 2, 2014 @ 13:38

Or put another way…

“Instead of using addlistener you can call the event.proplistener constructor directly which creates a listener not tied to the lifecycle of the object being listened to”.

#5 Comment By John On September 10, 2014 @ 09:17


Is it possible using this method or others to listen to properties that are not considered observable? My example is that I’d like to listen for, and respond to, changes to a figure’s ‘Position’ property. Ordinarily I trigger this by using ResizeFcn, but in this case I want the behavior to be triggered afterwards.

I tried (from memory…)

lh = addlistener(fignum, 'Position', 'PostSet', @mypostresizefcn);

and MATLAB accepted this without error, but actually ignored it – evidently since Position is not observable. (MATLAB should at least give me an error to tell me that my listener is not acceptable.)


#6 Comment By Yair Altman On September 10, 2014 @ 10:17

@John – I do not know of a way to listen to non-observable properties. Perhaps there is a way, but I don’t know it.

#7 Comment By Erik On May 4, 2015 @ 11:58

@John – Not the most elegant solution – but you could try to listen for an Event that always executes when position is changed. Using Matlab 2015a; for example, to determine potential event names for an axes position change:

hAxes = axes;
md = ?matlab.graphics.axis.Axes;
eventNames = {md.EventList.Name};
for iEvent = 1:numel(eventNames)
    addlistener(hAxes, eventNames{iEvent}, @(~,~) disp(eventNames{iEvent}));

And then change your axes position in various manners to see what Events occur. My very-quick testing indicates Events {‘MarkedDirty’, ‘LocationChanged’, ‘SizeChanged’, ‘MarkedClean’} are called in that order.

Keep in mind some Events {‘MarkedDirty’, ‘MarkedClean’} are called for all sorts of (non-position related) reasons.

#8 Comment By Julian On April 11, 2016 @ 10:31

Hi John,

you can listen to a ‘SizeChanged’ Property in HG2 handling

h = addlistener(gcf,'SizeChanged',@func);

#9 Comment By Collin Pecora On September 24, 2016 @ 00:58

Is there a way to listen for property changes of ‘pure’ java objects created in matlab?

Specificaly, I would like to listen to the value property of a jFormattedTextField as suggested by the javadocs

#10 Comment By Ofer Saferman On October 24, 2018 @ 12:58

How do you know which properties are observable?
Can you in general listen to your own added properties using setappdata? How to make them observable?

#11 Comment By Yair Altman On October 24, 2018 @ 13:30

@Ofer – you need to set the GetObservable meta-attribute to enable listening to PreGet/PostGet events, and similarly set SetObservable for PreSet/PostSet events. For example:

hObj = gcf;  % current figure (can be any handle)
hProp = addprop(hObj,'Yair');
hProp.SetObservable = true;
hObj.Yair = 2;  % "123" will be displayed in the Matlab console

If you forget to set the GetObservable/SetObservable meta-attribute, you will receive a run-time error when you try to call addlistener:

Error using matlab.ui.Figure/addlistener
While adding a PostSet listener, property 'Yair' in class 'matlab.ui.Figure' is not defined to be SetObservable. 

#12 Comment By rohit On January 29, 2019 @ 09:07


Can we attach a listener to “text” uicontrol ? So that whenever “String” property of “text” control changes, we can detect it ?

#13 Comment By Yair Altman On January 29, 2019 @ 12:37

@Rohit – yes you can, but I have no idea why you’d want to do this. After all, text controls are typically changed programmatically (not interactively) so you can call your requested functionality whenever you modify the text.

In any case, here’s how you can attach the requested callback:

hText = uicontrol('Style','text', ...);
hProp = findprop(hText,'String');
callback = @(h,e) disp(hText.String);  % your callback function handle
hListener = addlistener(hText, hProp, 'PostSet', callback);

#14 Comment By Rohit On January 29, 2019 @ 13:56

The reason to attach a listener is that, we have a Matlab tool in which “Text control” is written programmatically at 1000’s places. Now, I have introduced a “Message Log Panel” in which I want to put the same messages that were written to “Text control”. Either I go to 1000’s places and place my code to write messages to “Log Panel” or attach a listener to “text control” such that whenever any messages is written to “text control”, it automatically comes to the “Log panel” as well.

BTW, thanks , your suggestion worked..!

Article printed from Undocumented Matlab: https://undocumentedmatlab.com

URL to article: https://undocumentedmatlab.com/articles/property-value-change-listeners

URLs in this post:

[1] addlistener: http://www.mathworks.com/help/matlab/ref/handle.addlistener.html

[2] SetObservable and/or GetObservable attribute turned on: http://www.mathworks.com/help/matlab/matlab_oop/listening-for-changes-to-property-values.html#brkimdj-1

[3] explained here: http://undocumentedmatlab.com/blog/udd-events-and-listeners

[4] UDD Events and Listeners : https://undocumentedmatlab.com/articles/udd-events-and-listeners

[5] copyobj behavior change in HG2 : https://undocumentedmatlab.com/articles/copyobj-behavior-change-in-hg2

[6] Setting class property types : https://undocumentedmatlab.com/articles/setting-class-property-types

[7] Handle object as default class property value : https://undocumentedmatlab.com/articles/handle-object-as-default-class-property-value

[8] Getting default HG property values : https://undocumentedmatlab.com/articles/getting-default-hg-property-values

[9] xlsread functionality change in R2012a : https://undocumentedmatlab.com/articles/xlsread-functionality-change-in-r2012a

[10] : http://www.mathworks.co.uk/help/matlab/ref/event.proplistener.html

Copyright © Yair Altman - Undocumented Matlab. All rights reserved.