Advertisement
Guest User

Untitled

a guest
Jun 18th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. /*
  2. The following function creates a Proxy object with event methods attached.
  3. This might be useful for adding api calls or data checks whenever your object changes.
  4.  
  5. Example use case:
  6. On the client side you keep a data object which stores user or app data,
  7. whenever a key is changed you make an api call to write this new object to your database.
  8. */
  9.  
  10. export const watchObj = <T extends {}, V extends T[keyof T]>(
  11. /** Base Object to attach watchers */
  12. obj: T,
  13.  
  14. /** Event that triggers pre get */
  15. preGet?: (
  16. targetRef?: T,
  17. property?: keyof T
  18. ) => void ,
  19.  
  20. /** Event that fires after setting key value pair in object */
  21. afterSet?: (
  22. targetRef?: T,
  23. property?: keyof T,
  24. value?: V,
  25. beforeSetValue?: V | undefined
  26. ) => void,
  27.  
  28. /** Event that triggers after delete attempt */
  29. afterDelete?: (
  30. targetRef?: T,
  31. property?: keyof T,
  32. deletedValue?: V | undefined
  33. ) => void
  34. ) => {
  35.  
  36. const get = (targetRef: T, property: keyof T) => {
  37. if (preGet) {
  38. preGet(targetRef, property);
  39. }
  40. return targetRef[property];
  41. };
  42.  
  43. const set = (targetRef: T, property: keyof T, value: V) => {
  44. const currentValue = targetRef[property] as V | undefined;
  45. targetRef[property] = value;
  46. if (afterSet) {
  47. afterSet(targetRef, property, value, currentValue);
  48. }
  49. return true;
  50. };
  51.  
  52. const deleteProperty = (targetRef: T, property: keyof T) => {
  53. const valToDelete = targetRef[property] as V | undefined;
  54. if (property in targetRef) {
  55. delete targetRef[property];
  56. }
  57. if (afterDelete) {
  58. afterDelete(targetRef, property, valToDelete);
  59. }
  60. return true;
  61. };
  62.  
  63. return new Proxy(obj, { get, set, deleteProperty });
  64. };
  65.  
  66.  
  67.  
  68.  
  69.  
  70. // Example Code
  71.  
  72. type testObj = {
  73. test?: string;
  74. };
  75. const t: testObj = {};
  76. const onGet = (targetRef?: testObj, property?: keyof testObj) => {
  77. console.log(property); // prints test since this is the property being looked up
  78. };
  79.  
  80. const x = watchObj<testObj, testObj[keyof testObj]>(t, onGet);
  81. console.log(x.test); // prints undefined since there is no test key in the object
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement