There are two ways to create listeners:
handle.addlistener
creates a coupling between the listener and event source object. The listener object persists until you delete it or until the event object is destroyed. When the event source object is destroyed, MATLAB®automatically destroys the listener object.
handle.listener
constructs listener objects that are not coupled to the lifecycle of the event source object. The listener is active as long as the listener object remains in scope and is not explicitly deleted. Therefore, your application must maintain a reference to the listener object by storing the listener handle. The advantage of uncoupling the listener and event objects is that you can define and destroy each independently.
For more information, seeEvents and Listeners Syntax.
Theaddlistener
method returns the listener object so that you can set its properties. For example, you can temporarily disable a listener by setting itsEnabled
property tofalse
:
ListenerHandle.Enabled = false;
To reenable the listener, setEnabled
totrue
.
ListenerHandle.Enabled = true;
Callingdelete
on a listener object destroys it and permanently removes the listener:
delete(ListenerHandle)
Do not use thepack
command with objects that define events and listeners. Thepack
command causes the destructor of any listeners defined for the objects in the workspace. For information on restoring listeners when saving objects, seeRestore Listeners.