当我尝试在blazor组件初始化时订阅事件时,每次刷新或导航页面时,都会一次又一次地调用OnInitializedAsync方法,然后事件的调用列表会大大增加。如何限制仅连接一次?
@code {
[Parameter]
public CustomerModel model { get; set; }
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
model.PropertyChangedEvent += PropertyChanged;
}
}
通常,无论何时绑定事件,我都会先解除绑定。这是为了确保只有一个相同的处理程序只绑定一次。
model.PropertyChangedEvent -= PropertyChanged;
model.PropertyChangedEvent += PropertyChanged;
实现IDispoable
以取消订阅事件。
@implement IDisposable
...
@code {
[Parameter]
public CustomerModel model { get; set; }
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
model.PropertyChangedEvent += PropertyChanged;
}
public void Dispose()
{
model.PropertyChangedEvent -= PropertyChanged;
}
}