I get this error if I do not call InitView in the button click event:
View.Main.pas:57 Uncaught TypeError: Cannot read properties of null (reading 'SayHello')
at Object.btnHelloClick (View.Main.pas:57:12)
at Object.cb [as FOnClick] (rtl.js:254:1)
at Object.Click (WEBLib.Controls.pas:1854:5)
at Object.Click (WEBLib.StdCtrls.pas:3673:3)
at Object.HandleDoClick (WEBLib.Controls.pas:3925:5)
at HTMLButtonElement.cb (rtl.js:250:1)
I will eventually access a REST server from the interface to populate the Web form. I'm new to Web Core so I wanted to start by simply adding an interface to the form that would write "Hello World" to the console.
I create an interface:
unit Int.Main;
{$M+}
interface
type
IViewModelMain = interface
['{48B17B44-9FE7-4A02-9F16-D3852042B3BC}']
procedure SayHello;
end;
implementation
end.
and a class:
unit ViewModel.Main;
interface
uses
Int.Main
;
type
TViewModelMain = class(TInterfacedObject, IViewModelMain)
public
procedure SayHello;
end;
implementation
uses
Web
;
procedure TViewModelMain.SayHello;
begin
console.Log('Hello World');
end;
end.
I have a web form with a button and a field FViewModel that is IViewModel interface.. I added an initialization method InitView to Create the ViewModel interface and assign it to the field. I tried calling the IInitView from the forms Create and Show methods, but get the above error.I added console logging to both the Create and Show methods but there is no logging when I run the app, and I get the above error.
If I add the InitView method to the OnClick handler it logs the event and the interface call to SayHello. Here is the Form code:
unit View.Main;
interface
uses
Int.Main,
System.SysUtils,
System.Classes,
js,
web,
WEBLib.Graphics,
WEBLib.Controls,
WEBLib.Forms,
WEBLib.Dialogs,
WEBLib.Menus,
WEBLib.StdCtrls,
Vcl.Controls,
Vcl.StdCtrls;
type
TfrmMain = class(TWebForm)
lblHeader: TWebLabel;
btnHello: TWebButton;
procedure WebFormCreate(Sender: TObject);
procedure btnHelloClick(Sender: TObject);
procedure WebFormShow(Sender: TObject);
private
ViewModel : IViewModelMain;
procedure InitView;
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
uses
ViewModel.Main;
procedure TfrmMain.WebFormCreate(Sender: TObject);
begin
console.Log('TfrmMain.WebFormCreate');
InitView; // <- Not Initialized
end;
procedure TfrmMain.InitView;
begin
console.Log('TfrmMain.InitView');
ViewModel := TViewModelMain.Create;
end;
procedure TfrmMain.btnHelloClick(Sender: TObject);
begin
// InitView; // <- Initialized
ViewModel.SayHello;
end;
procedure TfrmMain.WebFormShow(Sender: TObject);
begin
console.Log('TfrmMain.WebFormShow');
InitView; // <- Not Initialized
end;
end.