image thumbnail

What's New for Object-Oriented Programming in MATLAB Webinar - Code Examples

by

 

10 Apr 2008 (Updated )

Code examples used in "What's New for Object-Oriented Programming in MATLABĀ®" Webinar

Events and listeners

Events and listeners

To monitor an object you first need to add an event to the class definition of the object, such as in this example. (see ev.m). Here we add an event called SavedData to this class which denotes when the class saves some data to disk. It could then be accessed by someone else.

It is the responsibility of the class to fire the event whenever it wants by calling the notify function in a method such as in the updateData method.

Contents

Monitoring an object

To monitor a object's events, you need to...

  • Create a call back function {see evcallback} what you would like executed when the event is fired. Here it just displays some text
  • Create the object to monitor
a=ev;
  • Add a listener to the object specifying this callback
lh=addlistener(a,'SavedData',@evCallback);
  • When the method that includes the notify call is executed, we see the call back is called
updateData(a);
Data was saved

There are also special events that let you monitor things such as property changes for example. The property has to specify the SetObservable attribute.

Following code need SetObservable to be added

Note that, if you modify and save a classdef file, it will not be used if there are existing workspace objects based on or inheriting from that definition file. You will get a warning. I will try to use the new object.

%a=ev

When this happens, use the clear command to remove those variables.

%clear
%a=ev % I will create again

Now we will add a listener to execute a callback whenever the data property of the object changes {step, step}

%lh2=addlistener(a,'data','PostSet',@evDataCallback);

When the property's value changes the call back is executed

%a.data=5;

Contact us