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;
现在我们必须在代码中的某处创建这个类的实例(例如在表单的创建事件中):
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 时,我们的脚本被编译并执行: