Calling custom class callback?

조회 수: 9 (최근 30일)
Marc Elpel
Marc Elpel 2021년 3월 11일
편집: Harsh Mahalwar 2024년 3월 15일
I have an app designer class (call it ClassA) which is calling functions in a second class (ClassB), where ClassB needs to have a callback to ClassA. The code appears to correctly pass the function to the Callback, but when trying to use the callback it errors out with "Unrecognized function or variable 'MyCallback'." MyCallback is a public function within ClassA.
MyClassB = ClassB(@MyCallback); % Instantiate Class B passing the Callback
MyClassB.Execute(); % Run my code in Class B
Then in the ClassB Code call the callback:
obj.CallBack_Fcn(); % The callback is stored to this property when ClassB is instantiated (obj is ClassB here)
When readback obj.CallBack_Fcn = @MyCallback; - there is no reference to the class which passed it.
The callback is always the same and based on some online searches I've tried various options including:
ClassA('MyCallback');
ClassA(obj.CallBack_Fcn);
ClassA.(obj.CallBack_Fcn);
ClassA.obj.CallBack_Fcn();
Suggestions?

답변 (1개)

Harsh Mahalwar
Harsh Mahalwar 2024년 3월 1일
편집: Harsh Mahalwar 2024년 3월 15일
Hi Marc,
From what I can gather, you are trying to call a callback function from classB which is a public function defined in classA.
The format to call a function present in a class is:
[object of the class].[name of the function]
Here’s an example on how you can declare the public function from classA into the parameters of classB:
(classA)
classdef classA
methods (Access = public)
function obj = classA()
disp("Constructor class A");
end
function sampleCallBack(obj)
disp("This is a sample callback message");
end
end
end
(classB)
classdef classB
methods(Access = public)
function obj = classB(callback)
callback();
disp("Constructor class B")
end
end
end
As shown in above example, we were able to call a public method in classA from classB.
“When readback obj.CallBack_Fcn = @MyCallback; - there is no reference to the class which passed it”
To access a property or a method from a class, you need to use class objects in MATLAB. Without a class object MATLAB wouldn’t know which [class and method] you are trying to use.
You can learn more about calling a function defined in a class using the following stack overflow thread:
I hope this helps, thanks!

카테고리

Help CenterFile Exchange에서 Handle Classes에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by