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 toaddlistener
orlistener
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 package:PackageName.functionName
lh = addlistener(eventSourceObj,'EventName',@PackageName.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
这是一个普通的语法的方法。的输入ut arguments (arg1,...argn
) must be defined in the context in which you calladdlistener
.
lh = addlistener(src,'EventName',@(src,evnt)obj.callbackMethod(src,evnt,arg1,...argn)
Usevarargin
to define the callback function.
function callbackMethod(src,evnt,varargin) arg1 = varargin{1}; ... argn = varargin{n}; ... end
For general information on anonymous function, seeAnonymous Functions.
Using Methods for Callbacks
TheTestAnonyFcn
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.
classdefTestAnonyFcn < handleeventsUpdateendmethodsfunctionobj = TestAnonyFcn t = datestr(now); addlistener(obj,'Update',@(src,evnt)obj.evntCb(src,evnt,t));endfunctiontriggerEvnt(obj) notify(obj,'Update')endendmethods(Access = private)functionevntCb(~,~,evnt,varargin) disp(['Number of inputs: ',num2str(nargin)]) disp(evnt.EventName) disp(varargin{:})endendend
Create an object and trigger the event by calling thetriggerEvt
method:
obj = TestAnonyFcn; obj.triggerEvnt;
Number of inputs: 4 Update 01-Jul-2008 17:19:36