Why does a listener object, created with the addlistener function, still exist after the deletion of its source event?
12 views (last 30 days)
Show older comments
MathWorks Support Team
on 11 Aug 2020
Answered: MathWorks Support Team
on 11 Aug 2020
"When the event source object is destroyed, MATLAB® automatically destroys the listener object."
However, running the following code shows that the listener object 'v' still exists after the deletion of its source event, i. e. the figure 'f':
>> f = uifigure();
>> v = addlistener(f, 'ObjectBeingDestroyed', @(src, event) disp('ja'))
>> delete(f);
>> v
This issue has been discussed on MATLAB Answers, see link: https://www.mathworks.com/matlabcentral/answers/510296-listener-object-not-destroyed .
This behaviour seems to be contrary to the documentation. What is the expected behaviour?
Accepted Answer
MathWorks Support Team
on 11 Aug 2020
The addlistener function allows code to attach a listener to one or more sources so that the listener will be referenced by the source object(s) and stay around at least as long as any of the source object(s) stays around provided the listener is not explicitly destroyed. When the source object(s) is/are destroyed, the listener will be automatically destroyed if there is no other variable holding onto the listener. In the example code provided, the simplest way to make sure that the listener is destroyed when the source is destroyed is to not assign the output variable 'v':
>> f = uifigure();
>> addlistener(f, 'ObjectBeingDestroyed', @(src, event) disp('ja'))
>> delete(f);
In the code example in the question, the variable 'v' is holding onto the listener, which prevents it from being deleted. Thus, this is expected behaviour.
0 Comments
More Answers (0)
See Also
Categories
Find more on Develop uifigure-Based Apps in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!