What is the purpose of 'Events' in OOP in MATLAB?
7 views (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.
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.
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;
% displays all events of that class:
Events for class matlab.ui.control.UIAxes:
classdef MyClass < handle
function obj = MyClass()
% instantiate class
h = MyClass();
Events for class MyClass:
% existing event -> works, but no reaction because no listener is defined
% *no output*
% event not defined -> error
Error using MyClass/notify
Event 'idontexist' is not defined for class 'MyClass'.
Error in MyClass/fireNonExistingEvent (line 16)
Example with listener
% define a listener aka observer to react to event
function onMyEvent(evnt, src) % eventListener callback
% shows (listener callback was called)
MyClass with no properties.
EventData with properties:
Source: [1×1 MyClass]
Find more on Construct and Work with Object Arrays 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!