addlistener
Attaches a callback to an event or property change of a handle object.
Category: Programming > Classes
Syntax
lh = addlistener(obj, 'EventName', callback)
Calls callback whenever obj triggers the event.
lh = addlistener(obj, 'PropName', 'PostSet', callback)
Calls callback after the observable property PropName is set.
Description
Events let objects announce that something happened without knowing who is interested. A class declares an event in its events block and fires it with notify(obj, 'EventName'). Any number of listeners may be attached from outside, each with its own callback, and they run in the order they were created.
Unlike listener, addlistener ties the listener to the life of the source object: you do not have to keep lh in a variable for it to stay active.
Input arguments
obj- Handle object that defines the event.
'EventName'- Name of an event declared in the
eventsblock of the class. callback- Function handle called as
callback(src, evtdata), wheresrcis the object andevtdatacarries event information.
Output arguments
lh- An
event.listenerobject. The listener lives as long aslhor the source object exists;delete(lh)removes it.
Example
Listening to a built-in event
m = containers.Map();
lh = addlistener(m, 'ObjectBeingDestroyed', @(src, evt) disp('map destroyed'));
class(lh)
lh.EventName
event.hasListener(m, 'ObjectBeingDestroyed')
ans = 'event.listener'
ans = 'ObjectBeingDestroyed'
ans = logical
1
Notes
Events declared in a classdef work and run their callbacks when notified. The built-in ObjectBeingDestroyed event is registered but its callback is not run when the object is deleted. Example code in this wiki uses a built-in class because a script cannot define its own class.