MackinnonBuck / blazor-page-script

A Blazor component enabling per-page JavaScript initialization logic in statically rendered Blazor Web apps
MIT License
70 stars 7 forks source link

Event before and after enhanced navigation #6

Closed Markz878 closed 8 months ago

Markz878 commented 9 months ago

Hi, thanks for this package. I'm trying to use it in my Blazor SSR app.

I have a page with details elements, and whenever I perform an enhanced navigation within the page, the details elements close.

So what I think I need are 2 javascript events, one that happens before the enhanced navigation (for storing info about the details elements state), and one that happens after it (applying the open states to the details elements). Could you give me some guidance, or is it possible to add to this package?

MackinnonBuck commented 9 months ago

Hi @Markz878,

Blazor doesn't currently expose an event to run logic before an enhanced navigation, so unfortunately I don't think this library could expose the callback you're asking for in a straightforward way.

What you could do is add event listeners to each <details> element to revert changes that weren't caused by user input. I just tried the following and it seems to work well:

export function onLoad() {
  const detailsElement = document.getElementById('my-details');
  let shouldBeOpen = detailsElement.open;
  detailsElement.addEventListener('click', () => {
    shouldBeOpen = !detailsElement.open;
  });
  detailsElement.addEventListener('toggle', () => {
    detailsElement.open = shouldBeOpen;
  });
}

Hope this helps!

Markz878 commented 8 months ago

Thanks for the answer, this is a good workaround for this. Have you considered adding that "beforeEnhancedNavigation" event to Blazor?

MackinnonBuck commented 8 months ago

Have you considered adding that "beforeEnhancedNavigation" event to Blazor?

It doesn't look like we have an issue tracking that - please feel free to open one in https://github.com/dotnet/aspnetcore :-)