Listener Callback Syntax
Specifying Listener Callbacks
Callbacks are functions that execute when the listener receives notification of the event. Pass a function handle referencing the callback function to addlistener
or listener
when creating the listener.
All callback functions must accept at least two arguments:
The handle of the object that is the source of the event
An
event.EventData
object or an object that is derived from theevent.EventData
class.
Syntax to Reference Callback
For a function: functionName
lh = addlistener(eventSourceObj,'EventName',@functionName)
For an ordinary method called with an object of the class: obj.methodName
lh = addlistener(eventSourceObj,'EventName',@obj.methodName)
For a static method:ClassName.methodName
lh = addlistener(eventSourceObj,'EventName',@ClassName.methodName)
For a function in a namespace:nspname.functionName
lh = addlistener(eventSourceObj,'EventName',@nspname.functionName)
Input Arguments for Callback Function
Define the callback function to accept the required arguments:
function callbackFunction(src,evnt) ... end
If you do not use the event source and event data arguments, you can define the function to ignore these inputs:
function callbackFunction(~,~) ... end
For a method:
function callbackMethod(obj,src,evnt) ... end
Additional Arguments for Callback Function
To pass arguments to your callback in addition to the source and event data arguments passed by MATLAB®, use an anonymous function. Anonymous functions can use any variables that are available in the current workspace.
Syntax Using Anonymous Function
Here is the syntax for an ordinary method. The input arguments (arg1,...argn
) must be defined in the context in which you call addlistener
.
lh = addlistener(src,'EventName',@(src,evnt)obj.callbackMethod(src,evnt,arg1,...argn)
Use varargin
to define the callback function.
function callbackMethod(src,evnt,varargin) arg1 = varargin{1}; ... argn = varargin{n}; ... end
For general information on anonymous function, see Anonymous Functions.
Using Methods for Callbacks
The TestAnonyFcn
class shows the use of an anonymous function with an additional argument. The listener callback displays the inputs arguments to show how MATLAB calls the callback method.
classdef TestAnonyFcn < handle events Update end methods function obj = TestAnonyFcn t = datestr(now); addlistener(obj,'Update',@(src,evnt)obj.evntCb(src,evnt,t)); end function triggerEvnt(obj) notify(obj,'Update') end end methods (Access = private) function evntCb(~,~,evnt,varargin) disp(['Number of inputs: ',num2str(nargin)]) disp(evnt.EventName) disp(varargin{:}) end end end
Create an object and trigger the event by calling the triggerEvt
method:
obj = TestAnonyFcn; obj.triggerEvnt;
Number of inputs: 4 Update 01-Jul-2008 17:19:36