bindProps.mjs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Utilities
  2. import { eventName, isOn } from "./helpers.mjs";
  3. const handlers = new WeakMap();
  4. export function bindProps(el, props) {
  5. Object.keys(props).forEach(k => {
  6. if (isOn(k)) {
  7. const name = eventName(k);
  8. const handler = handlers.get(el);
  9. if (props[k] == null) {
  10. handler?.forEach(v => {
  11. const [n, fn] = v;
  12. if (n === name) {
  13. el.removeEventListener(name, fn);
  14. handler.delete(v);
  15. }
  16. });
  17. } else if (!handler || ![...handler]?.some(v => v[0] === name && v[1] === props[k])) {
  18. el.addEventListener(name, props[k]);
  19. const _handler = handler || new Set();
  20. _handler.add([name, props[k]]);
  21. if (!handlers.has(el)) handlers.set(el, _handler);
  22. }
  23. } else {
  24. if (props[k] == null) {
  25. el.removeAttribute(k);
  26. } else {
  27. el.setAttribute(k, props[k]);
  28. }
  29. }
  30. });
  31. }
  32. export function unbindProps(el, props) {
  33. Object.keys(props).forEach(k => {
  34. if (isOn(k)) {
  35. const name = eventName(k);
  36. const handler = handlers.get(el);
  37. handler?.forEach(v => {
  38. const [n, fn] = v;
  39. if (n === name) {
  40. el.removeEventListener(name, fn);
  41. handler.delete(v);
  42. }
  43. });
  44. } else {
  45. el.removeAttribute(k);
  46. }
  47. });
  48. }
  49. //# sourceMappingURL=bindProps.mjs.map