Main Content

Determine If Event Has Listeners

Do Listeners Exist for This Event?

Use the 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.

Note

When called, 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

Use 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.

Coding Patterns

  • Conditionalize the creation of event data and the call to notify using event.hasListener. For an object array a, determine if there are listeners before creating event data and triggering the event:

    if any(event.hasListener(a,'NameOfEvent'))
       evt = MyCustomEventData(...);
       notify(a,'NameOfEvent',evt)
    end
  • 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,'NameOfEvent');
    notify(a(ind),'NameOfEvent',evt)

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 SpecificA, SpecificB, and SpecificC is RootSuperclass. Therefore, event.hasListener can find listeners only for the RootEvent event, because it is the only event common to all array elements.

Heterogeneous array with class events

Create a heterogeneous array with the three most specific classes:

het = [SpecificA,SpecificB,SpecificC];
class(het)
ans

RootSuperclass
events(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:

event.hasListener(het,'ClassAEvent')
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:

event.hasListener(het(1),'ClassAEvent')

For more information about determining the class of heterogeneous arrays, see Designing Heterogeneous Class Hierarchies.

Related Topics