What is the purpose of 'Events' in OOP in MATLAB?
조회 수: 2 (최근 30일)
이전 댓글 표시
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
답변 (2개)
Ralph
2020년 11월 19일
편집: Ralph
2020년 11월 19일
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
Jan Kappen
2019년 12월 11일
편집: Jan Kappen
2019년 12월 11일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Handle Classes에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!