What is the purpose of 'Events' in OOP in MATLAB?
1 view (last 30 days)
Show older comments
I'm familiar with the concept of "event driven programming", but what are these 'events' for when using OOP in MATLAB? I don't see this concept in Python and C++. It seems needlessly convoluted unless there is some purpose I am not aware of. Thanks.
0 Comments
Answers (2)
Ralph
on 19 Nov 2020
Edited: Ralph
on 19 Nov 2020
Within a single class events are generally overkill and/or overly vague. You just deal with the state change explicitly (i.e. your method may call another method) and you often have some internal hierarchy (i.e. you call 'load data', 'analyze data', and 'plot data' in a specifc order).
The point of events is more for inter-class coordination. Suppose we had a vehicle project, with objects: dashboard, gastank, engine etc. And further suppose those objects (classes) are developed by different developers. The gastank developer can create an event 'low fuel' but that developer doesn't know/care how the system will respond. Meanwhile the dashboard developer can simply listen for the event to turn an indicator on/off.
0 Comments
Jan Kappen
on 11 Dec 2019
Edited: Jan Kappen
on 11 Dec 2019
The concept is the quite common concept of observer pattern.
If you want to fire (aka notify) named events that can be observed (by an listener), there must be an events section in a handle class containing that event.
I.e. you can create a new UIAxes object which has 3 events:
h = matlab.ui.control.UIAxes;
events(h)
% displays all events of that class:
Events for class matlab.ui.control.UIAxes:
ObjectBeingDestroyed
PropertyAdded
PropertyRemoved
Custom example:
%% MyClass.m
classdef MyClass < handle
events
myEvent
end
methods
function obj = MyClass()
end
function fireExistingEvent(obj)
notify(obj,'myEvent')
end
function fireNonExistingEvent(obj)
notify(obj,'idontexist')
end
end
end
In Matlab:
% instantiate class
h = MyClass();
list events
events(h)
% shows:
Events for class MyClass:
myEvent
ObjectBeingDestroyed
fire events
% existing event -> works, but no reaction because no listener is defined
h.fireExistingEvent()
% shows:
% *no output*
% event not defined -> error
h.fireNonExistingEvent()
% shows:
Error using MyClass/notify
Event 'idontexist' is not defined for class 'MyClass'.
Error in MyClass/fireNonExistingEvent (line 16)
notify(obj,'idontexist')
Example with listener
% define a listener aka observer to react to event
listener(h,'myEvent',@onMyEvent);
h.fireExistingEvent()
function onMyEvent(evnt, src) % eventListener callback
evnt
src
disp('onMyEventCalled')
end
% shows (listener callback was called)
evnt =
MyClass with no properties.
src =
EventData with properties:
Source: [1×1 MyClass]
EventName: 'myEvent'
onMyEventCalled
0 Comments
See Also
Categories
Find more on Handle Classes in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!