Suppose I have a class 'myClass' that I want to listen to. First, I need to write my class with an event:
classdef myClass < handle
properties
% list of properties
end
events
myEvent
end
methods
% ... we'll write this in a second!
end
end
Then, we build another class to contain data we would like to pass through. This class must inherit from event.EventData
:
classdef myEventData < event.EventData
properties
A
B
C
end
methods
function obj = myEventData(A, B, C)
obj.A = A;
obj.B = B;
obj.C = C;
end
end
end
Then, in a method where you want to pass your data, construct a myEventData
object and use notify
to raise the event:
methods
function getDataAndNotify(obj)
[A, B, C] = result_of_processing;
eventdata = myEventData(A, B, C);
notify(obj, 'myEvent', eventdata);
end
end
OK, now your class is set up to broadcast events. How do we listen to it?
Use addlistener
to set up the listener:
M = myClass;
myListener = addListener(M, 'myEvent', {@myListenerCallback});
Your callback must have at least two arguments. The first argument is the source of the event; the second is any data the event may have passed.
function myListenerCallback(obj, eventdata)
% ...
end
In this case, obj
will be the myClass
obj that raised the event, and eventdata
will be your myEventData
object that contains the data you passed. Access the data like you would properties of any other object, i.e., eventdata.A
, eventdata.B
, eventdata.C
.