addlistener question...
13 views (last 30 days)
Show older comments
I have created a listener which calls 'myfunction' whenever the limits of a certain set of axes changes:
addlistener(handles.axes1,'XLim', 'PostSet', @myfunction);
function myfunction
...
This works fine. Now I want to pass the handles structure to myfunction:
addlistener(handles.axes1,'XLim', 'PostSet',{@myfunction,handles});
function myfunction(handles)
...
However I recieve the error:
callbacks need to be of type function handle
I cannot pass handles, or any additional arguments to myfunction in this case. Why is this so? How would I set up a listener object properly?
0 Comments
Accepted Answer
Jan
on 20 Oct 2011
The posted example does not work on my computer under Matlab 2011b:
addlistener(handles.axes1,'XLim', 'PostSet', @myfunction);
function myfunction % ERROR
Calling the callback function fails, because it needs at least 2 inputs:
function myfunction(ObjH, EventData) % OK
If you need a third input:
addlistener(handles.axes1,'XLim', 'PostSet', ...
@(ObjH, EventData) myfunction(ObjH, EventData, handles));
function myfunction(ObjH, EventData, handles)
More Answers (2)
Walter Roberson
on 20 Oct 2011
addlistener(handles.axes1,'XLim', 'PostSet', @(varargin) myfunction(varargin{:}, handles.axes1);
Then
function myfunction(varargin)
handles = guidata(varargin{end});
...
end
0 Comments
aodhan
on 17 Jul 2013
First I wanted to say thanks jan, I was struggling to pass the handles object into my callback function.
I wanted to add an additional example that someone might find useful. It uses the trick above to update a text box "while" a slider is being moved, rather than just updating the value after the mouse has been released.
% first add a listener to your program. I added mine to the function that executes just before the UI is made visible.
addlistener(handles.sDamping_slider,'Value', 'PostSet', ...
@(ObjH, EventData) myfunction(ObjH, EventData, handles));
% Now define the actual function that gets called "myfunction"
val = get(handles.sDamping_slider,'Value');
set(handles.sDamping_edit, 'String', num2str(val))
0 Comments
See Also
Categories
Find more on Graphics Object Programming 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!