listener callback execution error

12 次查看(过去 30 天)
Hello,
Can you please help me understand the following error?
Two classes:
classdef ToggleButton < handle
properties
State = false
end
events
ToggledState
end
methods
function OnStateChange(obj,newState)
if newState ~= obj.State
obj.State = newState;
notify(obj,'ToggledState');
end
end
end
end
...
classdef RespondToToggle < handle
methods
function obj = RespondToToggle(toggle_button_obj)
addlistener(toggle_button_obj,'ToggledState',@obj.handleEvnt);
end
end
methods
function handleEvnt(toggle_button_obj,~)
if toggle_button_obj.State
disp('ToggledState is true')
else
disp('ToggledState is false')
end
end
end
end
>> button=ToggleButton; >> responder=RespondToToggle(button); >> OnStateChange(button,1) Warning: Error occurred while executing callback: Error using RespondToToggle/handleEvnt Too many input arguments.
Error in RespondToToggle>@(varargin)obj.handleEvnt(varargin{:}) (line 4) addlistener(toggle_button_obj,'ToggledState',@obj.handleEvnt);
Error in ToggleButton/OnStateChange (line 12) notify(obj,'ToggledState');
> In ToggleButton>ToggleButton.OnStateChange at 12 >>

采纳的回答

Guillaume
Guillaume 2016-3-15
Since handleEvnt is a method of the class RespondToToggle its first argument will be an object of type RespondToToggle. In addition, it will receive two arguments from the event, the object that triggers the event, and the event argument. Thus, the signature of the event handler should be:
function handleEvnt(obj, toggle_button_obj, ~) %obj could be replaced by ~
sidenote: for a proper OOP design State should have private write access.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Events 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by