Using the JavaScript reverse router
There is a major issue with the preceding JavaScript code; the way it computes the URL of the Items.delete
route is very fragile because it duplicates the route definition:
xhr.open('DELETE', '/items/' + btn.dataset.id);
If you change the route definition, you will also have to accordingly change the preceding line of code.
We can solve this issue by putting the route information in the HTML attributes, instead of putting the item ID, as follows:
<li> <a href="@routes.Items.details(item.id)">@item.name</a> @defining(routes.Items.delete(item.id)) { route => <button class="delete-item" data-url="@route.url" data-method="@route.method">Delete</button> } </li>
However, in practice, this approach does not scale; in practice, you often need to compute URLs from the client side. Fortunately, this is exactly what the JavaScript reverse...