Why wasn't the PreGet event triggered?

2 ビュー (過去 30 日間)
fa wu
fa wu 2023 年 8 月 31 日
回答済み: Kanishk 2024 年 9 月 4 日
Originally, this example was meant to validate the AbortSet property, but I've encountered another issue. The problem is that the PreGet event isn't triggering when it should.
obj_a=ClassAbortSet;
obj_b=ClassListener(obj_a);
obj_a.Data=5;
When I run “obj_a.Data=5;”, the get method is triggered(Why?Click here.), and the program jumps to `val = obj.Data;`. However, `addlistener(event_obj,'Data','PreGet',@obj.getDataFunc);` is not executed before this. Shouldn't `addlistener(event_obj,'Data','PreGet',@obj.getDataFunc);` be triggered before executing the get method?
Then, I executed the following code. The program directly jumps to the callback function - "getDataFunc" .
x=obj_a.Data
So there is a question here.Why doesn't the callback function - "getDataFunc" get triggered the first time when getting the Data, but it does when executing `x = obj_a.Data;` for the same Data?
classdef ClassAbortSet < handle
properties (SetObservable, GetObservable, AbortSet)
Data=5;
end
methods
function obj = ClassAbortSet(val)
if nargin > 0
obj.Data = val;
end
end
function val = get.Data(obj)
val = obj.Data;
disp('get.Data called')
end
function set.Data(obj,val)
obj.Data = val;
disp('set.Data called')
end
end
end
classdef ClassListener < handle
methods
function obj = ClassListener(event_obj)
addlistener(event_obj,'Data','PreGet',@obj.getDataFunc);
addlistener(event_obj,'Data','PreSet',@obj.setDataFunc);
addlistener(event_obj,'Data','PostSet',@obj.setDataFunc);
end
end
methods(Static)
function getDataFunc(src,evnt)
disp ('PreGet event triggered') %This is the key issue.
end
function setDataFunc(src,evnt)
switch evnt.EventName %事件名称
case 'PreSet'
disp ('PreSet event triggered')
case 'PostSet'
disp ('PostSet event triggered')
end
end
end
end

回答 (1 件)

Kanishk
Kanishk 2024 年 9 月 4 日
Hi,
I understand you are using listener to trigger PreGetCallback function.
In the code, setting the ‘Data’ property of ‘obj_a’ does not trigger the ‘PreGet’ listener as you are assigning value to it.
Assigning default value only calls the get.Datafunction. Assigning different value than default value of 5 will result in calling ‘PreSet’ and ‘PostSet’ triggers instead ofPreGet’ as it is mentioned in the example shared that "If you query the property value, the PreGet and PostGet events are triggered."
Here is the link to the statement
Assigning value to Property will not trigger the ‘PreGet’ Callback but querying will trigger it. This is why ‘x=obj_a.Data’ triggers ‘PreGet’ Callback.
Hope this helps!
Thanks

カテゴリ

Help Center および File ExchangeConstruct and Work with Object Arrays についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by