MATLAB Object-Oriented Programming

(Joyce) #1

Determine If Event Has Listeners


In this section...
“Do Listeners Exist for This Event?” on page 11-37
“Why Test for Listeners” on page 11-37
“Coding Patterns” on page 11-37
“Listeners in Heterogeneous Arrays” on page 11-38

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.

NoteWhen 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

Determine If Event Has Listeners..................... 11-

Free download pdf