Calling custom class callback?

5 views (last 30 days)
Marc Elpel
Marc Elpel on 11 Mar 2021
Edited: Harsh Mahalwar on 15 Mar 2024
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?

Answers (1)

Harsh Mahalwar
Harsh Mahalwar on 1 Mar 2024
Edited: Harsh Mahalwar on 15 Mar 2024
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!

Categories

Find more on Interactive Control and Callbacks 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!