MATLAB: How to limit the scope of a listener created by using ADDLISTENER in MATLAB 8.0(R2012b)

addlistenerevent listenerlifecyclelistenerMATLABscope

I need to create a listener handle whose lifecycle is not tied to the source of the event. ADDLISTENER does not create this type of a listener handle. I need to define a handle whose scope I can control. How do I do this?

Best Answer

A listener handle created using addlistener is tied to the object that is the source of the event. For eg.,
lh = addlistener(Hsource,'EventName',callback)
Here, the lifecycle of lh is same as the lifecycle of Hsource.
You can still control its scope by using the DELETE command as follows:
delete(lh)
Alternatively you can use event.listener, in this case the listener handle is not tied to the source of the event. Therefore, it does not exist outside the scope of its definition. Thus, no events outside the function will trigger this listener.