Main Content

Implement Property Set Listener

This example shows how to define a listener for a property set event. The listener callback triggers when the value of a specific property changes. The class defined for this example uses a method for a push-button callback and a static method for the listener callback. When the push-button callback changes the value of a property, the listener executes its callback on thePreSetevent.

This example defines a class (PushButton) with these design elements:

  • ResultNumber– Observable property

  • uicontrolpushbutton– Push-button object used to generate a new graph when its callback executes

  • A listener that responds to a change in the observable property

PushButton Class Design

ThePushButtonclass createsfigure,uicontrol,axesgraphics objects, and a listener object in the class constructor.

The push button's callback is a class method (namedpressed). When the push button is activated, the following sequence occurs:

  1. MATLAB®executes thepressedmethod, which graphs a new set of data and increments theResultNumberproperty.

  2. Attempting to set the value of theResultNumberproperty triggers thePreSetevent, which executes the listener callback before setting the property value.

  3. 侦听器回调使用事件数据获取n the handle of the callback object (an instance of thePushButtonclass), which then provides the handle of the axes object that is stored in itsAxHandleproperty.

  4. The listener callback updates the axesTitleproperty, after the callback completes execution, MATLAB sets theResultsNumberproperty to its new value.

classdefPushButton < handleproperties(SetObservable) ResultNumber = 1endpropertiesAxHandleendmethodsfunctionbuttonObj = PushButton myFig = figure; buttonObj.AxHandle = axes('Parent',myFig); uicontrol('Parent',myFig,...'Style','pushbutton',...'String','Plot Data',...'Callback',@(src,evnt)pressed(buttonObj)); addlistener(buttonObj,'ResultNumber','PreSet',...@PushButton.updateTitle);endendmethodsfunctionpressed(obj) scatter(obj.AxHandle,randn(1,20),randn(1,20),'p') obj.ResultNumber = obj.ResultNumber + 1;endendmethods(Static)functionupdateTitle(~,eventData) h = eventData.AffectedObject; set(get(h.AxHandle,'Title'),'String',['Result Number: ',...num2str(h.ResultNumber)])endendend

The scatter graph looks similar to this graph after three push-button clicks.

buttonObj = PushButton;

Related Topics