How do I update my code from using handle.listener to using addlistener?

2 views (last 30 days)
I have code that ran in older versions of MATLAB that created property listeners by using the handle.listener method. I found a documentation page saying that, instead of handle.listener, we should use addlistener. I tried replacing calls to handle.listener with calls to addlistener, but this did not work. What do I do?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 25 Feb 2021
Edited: MathWorks Support Team on 25 Feb 2021
First, please read the documentation for "addlistener". This will give you a range of options and allowed syntaxes for calling this function.
Second, here are the major differences between these two functions, argument-by-argument:
 - The first argument (the handle to the object) is exactly the same.
 - The second argument (the property that you want to listen to) can also stay the same. However, in "addlistener", there is the option to simply pass in the name of the parameter that you want to use as a string, rather than using the "findprop" function to find the meta property object.
 - For the third argument, remove the "Property" prefix. The four options for this argument are "PreSet", "PostSet", "PreGet", and "PostGet", which invoke the callback before or after the property is either queried or set.
 - The fourth argument requires a function handle, and does not support either string expressions or a cell array of a function handle and arguments. For more information about function handles, please see the documentation link below. This function handle should accept two arguments, and MATLAB will automatically pass in a "GraphicsMetaProperty" object and a "PropertyEvent" object in these two positions. I find that often it is easiest to ignore these two inputs entirely and pass in parameters as I show below.
I have written a simple example of how to use the "addlistener" functions, as well as how to create and use simple function handles. This example listens to a line's "LineStyle" property and prints it out.
>> line = plot(1:10);
>> fh = @(name, style) disp([name ' has line style ' style '.']);
>> addlistener(line, 'LineStyle', 'PostSet', @(hProp, eventData) fh('My line', line.LineStyle));
>> line.LineStyle = '--';
My line has line style --.
Modifying this example should give you a good idea of how to use this function.
 

More Answers (0)

Categories

Find more on Graphics Object Programming in Help Center and File Exchange

Products


Release

R2015b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!