addlistener question...

조회 수: 13 (최근 30일)
Frank
Frank 2011년 10월 20일
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?

채택된 답변

Jan
Jan 2011년 10월 20일
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
Frank
Frank 2011년 10월 21일
Awesome thanks.

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

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

aodhan
aodhan 2013년 7월 17일
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))

카테고리

Help CenterFile Exchange에서 Graphics Object Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by