PWA Fundvelo der Caritas.
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

UserDataProvider.cs 2.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using Microsoft.JSInterop;
  2. using System;
  3. using System.ComponentModel;
  4. using System.Threading.Tasks;
  5. namespace CaritasPWA.Shared {
  6. public sealed class UserDataProvider {
  7. private const string KeyName = "state";
  8. private readonly IJSRuntime _jsRuntime;
  9. private bool _initialized;
  10. private UserData _data;
  11. public event EventHandler Changed;
  12. public bool AutoSave { get; set; } = true;
  13. public UserDataProvider(IJSRuntime jsRuntime) {
  14. _jsRuntime = jsRuntime;
  15. }
  16. public async ValueTask<UserData> Get() {
  17. if (_data != null)
  18. return _data;
  19. // Register the Storage event handler. This handler calls OnStorageUpdated when the storage changed.
  20. // This way, you can reload the settings when another instance of the application (tab / window) save the settings
  21. if (!_initialized) {
  22. // Create a reference to the current object, so the JS function can call the public method "OnStorageUpdated"
  23. var reference = DotNetObjectReference.Create(this);
  24. await _jsRuntime.InvokeVoidAsync("BlazorRegisterStorageEvent", reference);
  25. _initialized = true;
  26. }
  27. // Read the JSON string that contains the data from the local storage
  28. UserData result;
  29. var str = await _jsRuntime.InvokeAsync<string>("BlazorGetLocalStorage", KeyName);
  30. if (str != null) {
  31. result = System.Text.Json.JsonSerializer.Deserialize<UserData>(str) ?? new UserData();
  32. } else {
  33. result = new UserData();
  34. }
  35. // Register the OnPropertyChanged event, so it automatically persists the settings as soon as a value is changed
  36. result.PropertyChanged += OnPropertyChanged;
  37. _data = result;
  38. return result;
  39. }
  40. public async Task Save() {
  41. var json = System.Text.Json.JsonSerializer.Serialize(_data);
  42. await _jsRuntime.InvokeVoidAsync("BlazorSetLocalStorage", KeyName, json);
  43. }
  44. // Automatically persist the settings when a property changed
  45. private async void OnPropertyChanged(object sender, PropertyChangedEventArgs e) {
  46. if (AutoSave) {
  47. await Save();
  48. }
  49. }
  50. // This method is called from BlazorRegisterStorageEvent when the storage changed
  51. [JSInvokable]
  52. public void OnStorageUpdated(string key) {
  53. if (key == KeyName) {
  54. // Reset the settings. The next call to Get will reload the data
  55. _data = null;
  56. Changed?.Invoke(this, EventArgs.Empty);
  57. }
  58. }
  59. }
  60. }