diff --git a/docs/reference/src/language/builtins/callbacks.md b/docs/reference/src/language/builtins/callbacks.md index bbe678118..ee298fb8e 100644 --- a/docs/reference/src/language/builtins/callbacks.md +++ b/docs/reference/src/language/builtins/callbacks.md @@ -31,18 +31,33 @@ export component MyWindow inherits Window { ``` Don't use this callback to initialize properties, because this violates the declarative principle. -Avoid using this callback, unless you need it, for example, in order to notify some native code: + +Even though the `init` callback exists on all components, it cannot be set from application code, +i.e. an `on_init` function does not exist in the generated code. This is because the callback is invoked during the creation of the component, before you could call `on_init` to actually set it. + +While the `init` callback can invoke other callbacks, e.g. one defined in a `global` section, and +you _can_ bind these in the backend, this doesn't work for statically-created components, including +the window itself, because you need an instance to set the globals binding. But it is possible +to use this for dynamically created components (for example ones behind an `if`): ```slint,no-preview -global SystemService { +export global SystemService { // This callback can be implemented in native code using the Slint API callback ensure_service_running(); } -export component MySystemButton inherits Rectangle { +component MySystemButton inherits Rectangle { init => { SystemService.ensure_service_running(); } // ... } + +export component AppWindow inherits Window { + in property show-button: false; + + // MySystemButton isn't initialized at first, only when show-button is set to true. + // At that point, its init callback will call ensure_service_running() + if show-button : MySystemButton {} +} ```