Let's take a look at a couple of examples of using the Window API from our Give & Get site (template).
First, let's take a look at using the current visitor's location.
We use a visitor's location in a number of places in the site:
In all the places listed, we only need the visitor's latitude and longitude coordinates. However, the getCurrentGeolocation()
function may return a lot more information.
Instead of repeating the code to get the visitor's location data and extract the coordinates each time we need them, we create a function in a Public file that can be called anywhere in our code. We can reuse the public function whenever we need it.
Remember, we need to handle the cases where the location data is not available.
Here we begin by importing the Window API and then creating an exported function that can be called from anywhere in the rest of the site's code.
Next, we call the getCurrentGeoLocation()
function. If the Promise resolves we destructure the location data and only save the location coordinate data.
Then, we further destructure the returned location data so that we are left with only the latitude and longitude coordinates. Then we return them.
If the Promise rejects, we return null
, to signify that we were unable to retrieve the visitor's location data.
We use lightboxes in a number of places:
Let's take a closer look at the delete confirmation lightbox.
The My Giveaways page displays all the giveaways the current visitor has uploaded using a repeater. In each repeater item, there is a button to delete that item's uploaded giveaway.
The code for the delete button's functionality is in the repeater's onItemReady
event handler.
Here you can see that when the delete button is clicked. The Delete Confirmation lightbox is opened and we send the item's title to the lightbox. The page now waits until the lightbox is closed.
We'll see what happens in the lightbox code in a moment. In the meantime, let's just say that when the lightbox is closed, it sends the message true
if the deletion has been confirmed.
So we continue the delete button's onClick
event handler by checking if the deletion was confirmed.
If it was confirmed, we remove the deleted giveaway from the Giveaways collection and update the repeater accordingly. If it was not confirmed, we do nothing.
Now let's take a look at the code in the lightbox.
Here, in the Delete Confirmation lightbox, we start by retrieving the data sent from the My Giveaways page. Remember, the page sends the title of the giveaway that is being deleted.
We take that title and display it in a text element.
Then, we add an onClick
event handler to the button that confirms the deletion. The event handler closes the lightbox and sends a message back to the page signifying that the deletion has been confirmed.
If the visitor closes the lightbox using any other method, no message will be sent back to the page and the page will know that the deletion has not been confirmed.