[Pas2js] External class with custom event

Michael Van Canneyt michael at freepascal.org
Mon May 22 10:49:53 CEST 2023



On Mon, 22 May 2023, Luca Olivetti via Pas2js wrote:

> Hello,
>
> with the help of chatGPT I defined a wrapper for
>
> https://github.com/Choices-js/Choices
>
> now, that class fires a custom event
>
> https://github.com/Choices-js/Choices#events
>
> how can I wrap that?
>
> What I'm doing now is quite cumbersome/inelegant (here I'm trying to get the 
> value of the selection):
>
> procedure TMyApplication.BindElements;
> begin
> theselect:=TJSHTMLSelectElement(document.getElementById('choices-test'));
> thechoice:=TChoices.new(theselect,new([
>    'allowHTML', true
>    ]));
>  thechoice.setChoices(
>    [
>      new(['value','a','label','valor a']),
>      new(['value','b','label','valor b']),
>      new(['value','c','label','valor c'])
>    ],'value','label',true
>  );
>  theselect.addEventListener('choice', at ShowSelection);
> end;
>
>
> procedure TMyApplication.ShowSelection(event: TJSEvent);
> var
>  detail,choice: TJSObject;
>  value: JSValue;
> begin
>  detail:=TJSObject(event.Properties['detail']);
>  console.log(detail);
>  choice:=TJSObject(detail.Properties['choice']);
>  console.log(choice);
>  value:=choice.Properties['value'];
>  console.log(value);
> end;
>
>
> gpt suggestion (that I didn't try because the "external name 'Event'" is 
> already used for the definition of TJSEvent) is:
>
> type
>  TEvent = class external name 'Event'
>  public
>    property target: TJSObject; external name 'target';
>    property currentTarget: TJSObject; external name 'currentTarget';
>    property type_: string; external name 'type';
>    property detail: TJSObject; external name 'detail';
>    // Add other properties and methods as needed
>  end;

You can reuse a external name.

The chatGPT suggestion is not quite correct.

One of the following should do it.

type
   // read-only properties
   TMyDetail = class external name 'Event' (TJSObject)
   private
     fchoice : TJSObject; external name 'choice';
   public
     property choice : TJSObject read fchoice;
   end;

   TMyEvent = class external name 'Event' (TJSEvent)
   Private
     fdetail : TMyDetail; external name 'detail';
   public
     property detail: TJSObject read fChoice;
   end;

Or
   // Read-write properties can be replaced with simple fields.

   TMyDetail = class external name 'Event' (TJSObject)
     choice : TJSObject; external name 'choice';
   end;

   TMyEvent = class external name 'Event' (TJSEvent)
     detail : TMyDetail; external name 'detail';
   end;

Michael.


More information about the Pas2js mailing list