Calling custom class callback?

9 次查看(过去 30 天)
Marc Elpel
Marc Elpel 2021-3-11
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 中查找有关 Interactive Control and Callbacks 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by