MATLAB Object-Oriented Programming

(Joyce) #1

classdef RespondToToggle < handle
methods
function obj = RespondToToggle(toggle_button_obj)
addlistener(toggle_button_obj,'ToggledState',@RespondToToggle.handleEvnt);
end
end
methods (Static)
function handleEvnt(src,~)
if src.State
disp('ToggledState is true')
else
disp('ToggledState is false')
end
end
end
end


The class RespondToToggle adds the listener in its constructor. In this case, the class
defines the callback (handleEvnt) as a static method that accepts the two required
arguments:



  • src — The handle of the object triggering the event (that is, a ToggleButton object)

  • evtdata — An event.EventData object


For example, this code creates objects of both classes:


tb = ToggleButton;
rtt = RespondToToggle(tb);


Whenever you call the OnStateChange method of the ToggleButton object, notify
triggers the event. For this example, the callback displays the value of the State
property:


tb.OnStateChange(true)


ToggledState is true


tb.OnStateChange(false)


ToggledState is false


Remove Listeners


Remove a listener object by calling delete on its handle. For example, if the class
RespondToToggle saved the listener handle as a property, you could delete the listener.


classdef RespondToToggle < handle
properties


Events and Listeners Syntax
Free download pdf