dotnet / aspnetcore

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.
https://asp.net
MIT License
35.36k stars 9.99k forks source link

Add an hook for unobstrusive JavaScript post processing #14950

Closed BrightSoul closed 5 years ago

BrightSoul commented 5 years ago

Hello there, I'd like to execute a JavaScript callback function each time the DOM has been updated by a Razor Component rendering. This way I could implement some unobtrusive behavior in JavaScript. Suppose I have this code in my Razor Component.

<span data-publish-date="@publishDate.ToString("s")"></span>
@code {
   DateTime publishDate = new DateTime(2000, 1, 1);
}

Now, on the client side, as soon as the DOM has been updated, I'd like to execute a JavaScript function so I could look for elements with a data-publish-date attribute and do some post processing (e.g. set their innerText to a humanized date using Moment.js).

Maybe I could use a MutationObserver but I think a hook from Blazor is necessary to further improve JavaScript interop.

I've looked into the Blazor global object but I've found nothing interesting there. I've peeked into its _internal property but something tells me I should not fiddle with that one.

Blazor-global-object

Thanks, Moreno

javiercn commented 5 years ago

@BrightSoul Thanks for contacting us.

I think there are alternative ways to achieve what you are trying to accomplish.

You could create your own component and perform a JS interop call inside OnAfterRenderAsync to update the rendered markup, which would be a better approach than relying on unobtrusive javascript.

If you still want to keep your current approach, mutation observer is your best bet, but as I said, in the Blazor model, wrapping the behavior in a component is a better approach.