AFAIK DWScriptは、達成しようとしていることを直接サポートしていませんが、さまざまな方法で実装できます。ソースコードをどのように実装できるかを投稿しようと思いますが、おそらくニーズに合わせて調整する必要があります。
まず、スクリプトメソッドごとに分離する必要がある小さなラッパークラスを宣言します。
type
TDwsMethod = class
private
FDoExecute: TNotifyEvent;
FScriptText: string;
FDws: TDelphiWebScript;
FLastResult: string;
FMethod: TMethod;
protected
procedure Execute(Sender: TObject);
public
constructor Create(const AScriptText: string); virtual;
destructor Destroy; override;
property Method: TMethod read FMethod;
property LastResult: string read FLastResult;
published
property DoExecute: TNotifyEvent read FDoExecute write FDoExecute;
end;
constructor TDwsMethod.Create(const AScriptText: string);
begin
inherited Create();
FDoExecute := Execute;
FScriptText := AScriptText;
FDws := TDelphiWebScript.Create(nil);
FMethod := GetMethodProp(Self, 'DoExecute');
end;
destructor TDwsMethod.Destroy;
begin
FDws.Free;
inherited Destroy;
end;
procedure TDwsMethod.Execute(Sender: TObject);
begin
ShowMessage('My Method executed. Value: ' + FDws.Compile(FScriptText).Execute().Result.ToString);
end;
次に、コードのどこかにこのクラスのインスタンスを作成する必要があります(たとえば、フォームのcreateイベントで)。
procedure TMainForm.FormCreate(Sender: TObject);
begin
FDWSMethod := TDwsMethod.Create('PrintLn(100);'); //in constructor we pass script text which needs to be executed
//now we can set form's mainclick event to our DWS method
SetMethodProp(Self, 'MainClick', FDWSMethod.Method);
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
FDWSMethod.Free;
end;
MainClickを呼び出すと、スクリプトがコンパイルされて実行されます。
