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, ...

Get Play Framework Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.