addlistener question...

14 Ansichten (letzte 30 Tage)
Frank
Frank am 20 Okt. 2011
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?

Akzeptierte Antwort

Jan
Jan am 20 Okt. 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)
  1 Kommentar
Frank
Frank am 21 Okt. 2011
Awesome thanks.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (2)

Walter Roberson
Walter Roberson am 20 Okt. 2011
addlistener(handles.axes1,'XLim', 'PostSet', @(varargin) myfunction(varargin{:}, handles.axes1);
Then
function myfunction(varargin)
handles = guidata(varargin{end});
...
end

aodhan
aodhan am 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))

Kategorien

Mehr zu Graphics Object Programming finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by