MATLAB: Listener callback execution error

callbacklistenerMATLABoop

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 >>

Best Answer

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.