Trigger Events
The OnStateChange method calls notify to trigger the ToggledState event. Pass the
handle of the object that is the source of the event and the name of the event to notify.
classdef ToggleButton < handle
properties
State = false
end
events
ToggledState
end
methods
function OnStateChange(obj,newState)
if newState ~= obj.State
obj.State = newState;
notify(obj,'ToggledState');
end
end
end
end
Listen to Events
After the call to notify triggers an event, MATLAB broadcasts a message to all listeners
that are defined for that event and source object. There are two ways to create listeners:
using the handle class handle.addlistener or handle.listener method.
Use addlistener for Persistent Listeners
If you want the listener to persist beyond the normal variable scope, use addlistener to
create it. The event source object holds a reference to the listener object. When the event
source object is destroyed, MATLAB destroys the listener.
This code defines a listener for the ToggleState event:
lh = addlistener(obj,'ToggleState',@RespondToToggle.handleEvnt);
addlistener has these arguments:
- obj — The object that is the source of the event
- ToggleState — The event name passed as a char vector
Events and Listeners Syntax