MATLAB Object-Oriented Programming

(Joyce) #1
ListenerHandle % Property for listener handle
end
methods
function obj = RespondToToggle(toggle_button_obj)
hl = addlistener(toggle_button_obj,'ToggledState',@RespondToToggle.handleEvnt);
obj.ListenerHandle = hl; % Save listener handle
end
end
methods (Static)
function handleEvnt(src,~)
if src.State
disp('ToggledState is true')
else
disp('ToggledState is false')
end
end
end
end

With this code change, you can remove the listener from an instance of the
RespondToToggle class. For example:

tb = ToggleButton;
rtt = RespondToToggle(tb);

The object rtt is listening for the ToggleState event triggered by object tb. To remove
the listener, call delete on the property containing the listener handle.

delete(rtt.ListenerHandle)

To deactivate a listener temporarily, see “Temporarily Deactivate Listeners” on page 11-
28.

Define Event-Specific Data


Suppose that you want to pass the state of the toggle button as a result of the event to the
listener callback. You can add more data to the default event data by subclassing the
event.EventData class and adding a property to contain this information. Then you can
pass this object to the handle.notify method.

NoteTo save and load objects that are subclasses of event.EventData, such as
ToggleEventData, enable the ConstructOnLoad class attribute for the subclass.

classdef (ConstructOnLoad) ToggleEventData < event.EventData
properties

11 Events — Sending and Responding to Messages

Free download pdf