Observe Changes to Property Values - MATLAB & Simulink (original) (raw)

Main Content

This example shows how to listen for changes to a property value. This example uses:

classdef PropLis < handle % Define a property that is SetObservable properties (SetObservable) ObservedProp = 1 end methods function attachListener(obj) %Attach a listener to a PropListener object addlistener(obj,'ObservedProp','PostSet',@PropLis.propChange); end end methods (Static) function propChange(metaProp,eventData) % Callback for PostSet event % Inputs: matlab.metadata.Property object, event.PropertyEvent h = eventData.AffectedObject; propName = metaProp.Name; disp(['The ',propName,' property has changed.']) disp(['The new value is: ',num2str(h.ObservedProp)]) disp(['Its default value is: ',num2str(metaProp.DefaultValue)]) end end end

The PropLis class uses an ordinary method (attachListener) to add the listener for the ObservedProp property. If the PropLis class defines a constructor, the constructor can contain the call to addlistener.

The listener callback is a static method (propChange). MATLAB passes two arguments when calling this function:

These arguments provide information about the property and the event.

Use the PropLis class by creating an instance and calling its attachListener method:

plObj = PropLis; plObj.ObservedProp

plObj.attachListener plObj.ObservedProp = 2;

The ObservedProp property has changed. The new value is: 2 Its default value is: 1

See Also

event.proplistener | addlistener | listener

Topics