In this repository, bidirectional integration between Datastar and third-party JavaScript libraries is explored; namely, Google Maps JavaScript API serves as an example of such a library.
- Node.js installed
- Google Maps JavaScript API set up (set the API key here)
npm install && make develop-componentsand then navigate to http://localhost:5173/.
We proceed by wrapping the API in a Web component (see here). Then, achieving bidirectional data and control flow between the API and Datastar is quite straightforward.
The data flow from Datastar to the API is demonstrated by having the map centered at the coordinates specified in "Map center" (try it out!). The inputs feed the center signal using data-bind and the API web component, in turn, tracks the signal changes through data-attr; all we need to do is declare the center attribute as an observed attribute and implement the attributeChangedCallback.
The data flow from the API to Datastar is demonstrated by displaying the latest change to the polygon in "Polygon change" (try dragging and dropping the nodes of the polygon). The API events trigger custom events on the API component and the custom events, in turn, trigger changes to the event signal, which the read-only fields in "Polygon change" bind to using data-bind.
To see the control flow from Datastar to the API in action, click the "Reset map center" or "Reset polygon" button to reset the map center or the polygon, respectively. We leverage data-ref to store a reference to the API web component in a signal and then use the reference to call a method of the API web component whenever a button is clicked.
The control flow from the API to Datastar can be achieved by triggering custom events on the API web component - see above.