Dispose references when performing js-to-blazor interop
See original GitHub issueI’ve followed the “Call .NET from JavaScript” documentation. It shows how to pass a blazor reference to javascript, so the latter can invoke instance methods in the former. It works.
The doc also shows how to dispose references in c#.
But I don’t understand how the blazor <--> wasm <--> javascript
interop works, so I don’t know whether I must do any “disposal” in the javascript side. Would an unfreed reference in the js side affect the blazor side somehow, or would blazor automatically free the js module?
This is what I’ve done, based on that doc:
MyComponent.razor
@implements IAsyncDisposable
@code {
private IJSObjectReference _module;
private DotNetObjectReference<MyComponent> _ref;
protected override async Task OnInitializedAsync()
{
//...
_ref = DotNetObjectReference.Create(this);
await _module.InvokeVoidAsync("init", _ref);
}
public async ValueTask DisposeAsync()
{
await _module.InvokeVoidAsync("dispose"); // <----- necessary?
await _module.DisposeAsync();
_ref.Dispose();
}
[JSInvokable] public async Task FooHandled(string someData) { /* ... */ }
[JSInvokable] public async Task BarHandled(string someData) { /* ... */ }
// ...rest of code
}
MyComponent.razor.js
let _ref = null;
export function init(ref) {
_ref = ref;
}
export function dispose() { // <-----|
myComponent.removeEventListener("click", onClick); // |-- necessary?
_ref = null; // |
} // <-----|
export function foo() {
//...
_ref.invokeMethodAsync("FooHandled", someData);
}
export function bar() {
//...
_ref.invokeMethodAsync("BarHandled", someData);
}
// ...rest of code
I’m using a js module as shown in the docs (or should I use a js class instead?) Must I somehow free that js _ref
for the js garbage collector, or would blazor do that for me by freeing the entire js module?
Issue Analytics
- State:
- Created 10 months ago
- Comments:6 (6 by maintainers)
Yes that would be awesome, I’m looking forward to it. The current content is good too, I’ll reread all of it, thanks.
DotNetObjectReference
disposal on the JS-side is covered at the end of the following section …https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/call-dotnet-from-javascript?view=aspnetcore-7.0#class-instance-examples
… and then appears a little later in the Component instance .NET method helper class section example.
I’ll be improving all of our JS interop disposal guidance within a couple of weeks right after 7.0 work is finished. Currently, the client-side disposal guidance appears at the end of sections on general JS interop coverage that focuses on disposing from .NET … it’s just tacked on to the end of those sections. I think what I’ll end up doing is creating dedicated sections on disposal in both the Call .NET and Call JS articles that explains and demonstrates approaches.