MATLAB Object-Oriented Programming

(Joyce) #1

Observe Changes to Property Values


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


  • PostSet event predefined by MATLAB

  • SetObservable property attribute to enable triggering the property PostSet event.

  • addlistener handle class method to create the listener


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: meta.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:


  • metaProp — a meta.property object for ObservedProp

  • eventData — an event.PropertyEvent object contain event-specific data.


These arguments provide information about the property and the event.

Observe Changes to Property Values
Free download pdf