Deferred Initialization
A widget normally does all its work in its constructor: a grid creates its toolbar, view, columns and quick filters, a dialog its toolbar, tabs and form. That has two costs.
- The base constructor calls the overrides of a subclass before the subclass is constructed. A field of the
subclass, e.g.
readonly title = "Orders", has no value yet whengetInitialTitle()orgetButtons()reads it from the base constructor. - The constructor can't wait. A grid or a dialog needs its columns or form before it can build itself, so when they are not loaded yet, they are loaded with a blocking request, which freezes the page until it returns. Lookup editors do the same with their lookups.
A widget class can defer its initialization instead, by moving the work of its constructor to deferredInit():
export class OrderGrid extends EntityGrid<OrderRow> {
protected override async deferredInit() {
await super.deferredInit();
// what the constructor did
}
}
Its constructors then only take the props and the element, and the work runs in deferredInit(), once all the
constructors are done, where it may wait. A class that defers without overriding it, e.g. to load its columns
asynchronously, says so with the Attributes.deferInit() attribute:
export class OrderGrid extends EntityGrid<OrderRow> {
static override[Symbol.typeInfo] = this.registerClass(nsMyApp, [Attributes.deferInit()]);
}
Grids, entity dialogs and property dialogs load their columns or form asynchronously there, and the lookup editors of their forms load their lookups asynchronously too.
When Is It Initialized?
The ones that create widgets start the initialization by calling init(): JSX, Widget.create, gridPageInit, and
the dialogs that a grid opens. A widget created with new and never inited is initialized at the next microtask.
init() returns at once, so the widget may not be fully initialized when it does. What runs before the first wait is
done by then, e.g. the toolbar and the view of a grid, but not what needs the columns or the form. The code that needs
it all waits for initAsync(), which runs the initialization once and resolves when it is done:
export default async () => {
// the quick filters of the grid are there once it is initialized
const orderGrid = await gridPageInit(ProOrderGrid).initAsync();
orderGrid.set_shippingState(1);
}
A page init that creates a widget can return its initAsync(), which the page ignores, while a test can wait for
it:
export default function pageInit(opt: SignUpPageModel) {
return new SignUpPanel({ element: "#SignUpPanel", ...opt }).initAsync();
}
// in a test
await pageInit({});
init() keeps returning the widget, so chains like new PropertyGrid({ ... }).init() work as before. A widget whose
deferredInit() doesn't wait, e.g. a plain widget or a panel, is fully initialized when init() returns.
The methods that are usually called right after creating a widget wait for it themselves:
loadByIdAndOpenDialog,loadEntityAndOpenDialog,loadNewAndOpenDialoganddialogOpenof a dialog load and open it once it is initialized, so opening a dialog doesn't change. The callbacks ofload,loadByIdandloadByIdAndOpenDialogare called after that, with the entity loaded, and not at all when the dialog is destroyed before it finishes initializing.refresh()of a grid does nothing until it is initialized, as the grid loads its rows then anyway.setEqualityand the view of a grid can be used at once, as the view is created before the columns.readOnlyof an entity dialog can be set at once, and is applied when it loads an entity.
Anything else, e.g. dialog.form or grid.slickGrid, is there once initAsync() resolves.
A JSX ref callback runs when init() returns, so it may come before the form or the columns of a widget that
defers, e.g. while a panel loads its form. Code that uses them goes in the widget's deferredInit(), or waits for
initAsync().
A subclass can ask the widget where it is: usesDeferredInit tells whether the class defers its initialization,
initialized whether it is done, and initNow() starts it if it hasn't started and tells whether it is done at once,
so a method that may be called before the widget is ready can wait only when it has to:
protected setSelection(keys: number[]) {
if (!this.initNow())
return void this.initAsync().then(() => this.setSelection(keys));
// the quick filters and the view are there now
}
Writing a Class That Defers
The code that went in the constructor goes in deferredInit(), after the base:
export class CustomerDialog extends EntityDialog<CustomerRow> {
private readonly form = new CustomerForm(this.idPrefix);
protected override async deferredInit() {
await super.deferredInit();
// the fields, the form or the columns are all there now
this.form.Country.change(() => this.updateCities());
const lookup = await CountryRow.getLookupAsync();
// ...
}
}
What the base classes do in their deferredInit():
| Class | Before the first wait (in init()) |
Then |
|---|---|---|
DataGrid, EntityGrid |
contents, title, toolbar, view | columns (getPropertyItemsDataAsync), quick filters, filter bar, afterInit, the lookups of its quick filter editors, restoring the settings, then the first load |
EntityDialog |
contents, validator, tabs, toolbar | form (getPropertyItemsDataAsync), localizer, the lookups of its editors, afterInit |
PropertyDialog |
contents, validator, tabs, toolbar | form, the lookups of its editors, its initial entity, afterInit |
BasePanel |
contents, validator, tabs, toolbar | |
PropertyPanel |
contents, validator, tabs, toolbar, and the form and initial entity when the form is loaded already | form (loaded asynchronously), initial entity |
A grid or a dialog that defers loads its columns or form with getPropertyItemsDataAsync(), and a panel loads its
form asynchronously before it reads it. A class that gives its items by overriding only getPropertyItemsData(), or
getPropertyItems() without a script to load, still gets them from those methods, which is fine when it builds them
in code. A class that loads them, e.g. to change some of the items of its form, overrides
getPropertyItemsDataAsync() instead, as the sync method would load them with a blocking request, and changes a copy,
as the loaded form is shared:
protected override async getPropertyItemsDataAsync() {
const data = await super.getPropertyItemsDataAsync();
return {
...data,
items: data.items.map(x => x.name === "DetailList" ? { ...x, editorType: InlineOrderDetailsEditor } : x)
};
}
afterInit() of the dialogs and the grids is called where it was: right after the form or the columns are created,
before the code a subclass puts after await super.deferredInit(). A class that defers doesn't need it, as that code
runs at the same point, but one that keeps its afterInit() works too, and it may be async. propertyItemsReady may
be async as well.
BaseDialog.onAfterInit is raised once the whole deferredInit() is done, including the code of the subclasses, and
DataGrid.onAfterInit once the columns of a grid are created, before its afterInit, as before.
Using a Widget Too Early
Before its initialization starts, e.g. in a constructor, a widget that defers has no contents, and it has no form or columns until they are loaded:
- Reading an editor of its form, e.g.
this.form.Name, throws an error that tells the widget is not initialized yet. This needs a form created with the widget,new MyForm(this), not with its ID prefix. this.byId("Some")returns an empty result, and an event bound to it is never raised. In development (seeErrorHandling.isDevelopmentMode),byIdandfindByIdwrite a warning to the console for an element that they don't find before the initialization starts.viewandsleekGridof a grid, andpropertyGridof a dialog, are undefined until they are created.
The code that needs them goes to deferredInit(), after await super.deferredInit(), or after
await widget.initAsync() where the widget is created.
true, false and "optional"
A class says how it initializes with the Attributes.deferInit(value) attribute, in the attributes of its type info:
Attributes.deferInit(...) |
Meaning | The subclasses |
|---|---|---|
() or (true) |
The class defers its initialization: its constructor leaves work to deferredInit(). |
Inherit it, and must defer too. |
(false) |
The class initializes in its constructor, which uses what the base classes initialize. | Inherit it, and must initialize in their constructors too. |
("optional") |
The class supports both. | Don't inherit it. |
| none | true when the class overrides deferredInit(), else as a base class says, else as the application default says. |
A subclass can't change a true or false of a base class: e.g. a false under a true throws when the widget is
created, as one of them would run the wrong way.
A class that is not registered, e.g. a class of a test, adds it with
static { addCustomAttribute(this, Attributes.deferInit()); }.
Turning It On for an Application
The application default is Widget.defaultDeferInit, false unless the script init of the application turns it on,
which the Serene and StartSharp templates do:
// Modules/Common/script-init/deferinit-init.ts
import { Widget } from "@serenity-is/corelib";
Widget.defaultDeferInit = true;
Every class that says nothing, and has no base class that says true or false, then defers its initialization. The
framework classes that support both, "optional" ones, defer too. An application turns it on when its own widgets are
written that way; a class that isn't yet has Attributes.deferInit(false), which its subclasses inherit.
A test that creates a widget waits for it too, e.g. const dialog = await new MyDialog({}).initAsync().
Supporting Both
A class whose subclasses may or may not defer, e.g. a base class of a library, has Attributes.deferInit("optional"),
and runs the same private method from its constructor when it doesn't defer, and from deferredInit() when it does:
export class MyPanel<P> extends Widget<P> {
static override[Symbol.typeInfo] = this.registerClass(nsMyLib, [Attributes.deferInit("optional")]);
constructor(props: WidgetProps<P>) {
super(props);
if (!this.usesDeferredInit)
this.#sharedInit();
}
protected override deferredInit(): void | PromiseLike<void> {
return nowOrThen(super.deferredInit(), () => this.domNode ? this.#sharedInit() : undefined);
}
// private, so that a subclass can't override it, which would run in this constructor, before its own fields
#sharedInit() {
// what the constructor did
}
}
nowOrThen runs the callback at once when the base doesn't wait, and once it is done when it does, so the work
before the first wait is still done when init() returns, which await super.deferredInit() would delay, as await
always yields. Application classes can just await it.
"optional" is not inherited, so the subclasses of such a class follow the application default unless they say
otherwise. The framework classes that support both are BaseDialog, PropertyDialog, EntityDialog, DataGrid,
BasePanel, PropertyPanel, LookupEditorBase, LookupEditor, CheckTreeEditor, CheckLookupEditor, FilterPanel
and FilterDialog of corelib, ReportDialog of Serenity.Extensions, and ClientGrid and WizardDialog of the Pro
features. The rows and the grouping that are set on a ClientGrid before it is initialized are applied once it is.
When the Creator Asks
The creator of a widget can ask an "optional" class to defer, or not, with the deferInit prop:
new LookupEditor({ lookupKey: "Northwind.Customer", deferInit: true });
The other classes ignore it: a class that says true or false, or overrides deferredInit(), does as it says,
and one that says nothing follows the application default.
The quick filter bar of a grid asks its editors to do as the grid does too: in a grid that defers, a lookup quick filter
loads its lookup asynchronously, its init runs once it has its items, and the grid waits for them before it restores
its settings and loads its rows, so the first request has the values of the filters (QuickFilterBar.getEditorsLoading).
PropertyGrid, Toolbar, QuickFilterBar, QuickSearchInput, SlickPager and FilterDisplayBar always initialize
in their constructors, with Attributes.deferInit(false), as they have nothing to wait for, and the code that creates
them usually uses them at once.
The property grid of a form asks its editors to do as the form does. In a dialog that defers, a LookupEditor loads its
lookup with getLookupAsync(), and the dialog waits for its editors before it loads an entity, so the values of the
entity find their items. In a dialog that initializes in its constructor, it loads its lookup as before. A value set on a LookupEditor while it
loads its lookup, e.g. right after it is created, is kept and applied once it has its items.
Mistakes It Catches
The rules are checked when a widget is created, and these throw:
- a class that sets
falsebut overridesdeferredInit(), which would never run, or a subclass that setsfalseunder a class that overrides it; - a
deferInit()method, mixed up withdeferredInit(); - a
trueand afalsein the same chain of classes; - a value other than
true,falseor"optional".
Moving From useAsync and deferRender
useAsync()ofDataGrid,EntityDialogandPropertyDialogloaded the columns or the form asynchronously, but nothing waited for them, e.g. arefreshor aloadResponsethat came before them found no columns or form. It is deprecated: replace the override withAttributes.deferInit(), or move the work of the constructor todeferredInit().deferRender()ofWidgetis removed. It movedrenderContents()from the constructor toinit(), which a class that defers does too, with the rest of the constructor work.syncOrAsyncThenis still there for the classes that initialize in their constructors.