Callback/Signal in GDScript class

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By qazwsx
:warning: Old Version Published before Godot 3 was released.

How I can create a callback mechanism or signal in class. Let’s say I have created a class and I want to be able to execute a callback when some internal events happen.

I am wondering if something like that would be implemented for class. I suppose not as it is not a Node but only class:

class SimpleExample:
	signal my_signal

	func some_func():
		emit_signal(my_signal)

The callback that I wrote is also not ideal solution. For example:

class SimpleExample2:
	var my_callbacks = []

	func add_callback(fun_name):
		// check if not already added
		my_callbacks.append(fun_name)

	func some_func():
		// some interal calculations
		for fun in my_callbacks:
			call(fun)

But that will not work because my_callbacks are just strings so the call function do not know which node/object is the owner. It will simply try to run that name (fun) as the function.

:bust_in_silhouette: Reply From: vinod

For the callbacks to work, you also need to pass the object instance. You can see this format similar to the connect api in gdscript.

Inside the class you need to save the callback method and the instance in a dictionary format. The use call_deferred method to call it.

:bust_in_silhouette: Reply From: T0t4r4

In 3.2 at least you can use the funcref() function, as the example on this post shows.