Determine If Event Has Listeners
Do Listeners Exist for This Event?
event.hasListener function to determine if a specific event has listeners.
event.hasListener accepts an array of event source objects and an event name as input arguments. It returns an array of logical values indicating if listeners exist for the specified event on each object in the array.
event.hasListener must have
NotifyAccess for the event. That is, call
event.hasListener in a context in which you can call
notify for the event in question.
Why Test for Listeners
event.hasListener to avoid sending event notifications when there are no listeners for the event. For example, if creating custom event data consumes significant resources, or if events are triggered repeatedly, use
event.hasListener to test for listeners before performing these steps.
Conditionalize the creation of event data and the call to
event.hasListener. For an object array
a, determine if there are listeners before creating event data and triggering the event:
NameOfEvent')) evt = MyCustomEventData(...); notify(a,'
Trigger events selectively using logical indexing with the values returned by
event.hasListener. Send event notifications only for array elements that have listeners:
ind = event.hasListeners(a,'
Listeners in Heterogeneous Arrays
If the input object array is heterogeneous, the class of the array must define the specified event. You can query the listeners only for events that all objects in the array define.
For example, in the following diagram, the class of a heterogeneous array formed with objects of classes
event.hasListener can find listeners only for the
RootEvent event, because it is the only event common to all array elements.
Create a heterogeneous array with the three most specific classes:
het = [SpecificA,SpecificB,SpecificC]; class(het)
Events for class RootSuperclass RootEvent
event.hasListener cannot determine if there are listeners for events that are defined by some but not all objects in the array:
Error using event.hasListener Event 'ClassAEvent' is not defined for class 'RootSuperclass'.
Determine if individual objects in the heterogeneous array have listeners defined for their specific events, by indexing into the array:
For more information about determining the class of heterogeneous arrays, see Designing Heterogeneous Class Hierarchies.