MCPcopy Create free account
hub / github.com/Xu22Web/tech-study-js / handleAttribute

Function handleAttribute

tech-study.js:1477–1597  ·  view source on GitHub ↗

* @description 处理属性 * @param ele * @param key * @param value

(ele, key, value, subscribe, unsubscribe)

Source from the content-addressed store, hash-verified

1475 * @param value
1476 */
1477function handleAttribute(ele, key, value, subscribe, unsubscribe) {
1478 // 处理完的key
1479 const formatKey = key.toLowerCase();
1480 // 事件绑定
1481 if (formatKey.startsWith('on')) {
1482 // 事件监听
1483 const [event] = formatKey.match(/(?<=on).*/);
1484 // 事件类型
1485 if (event) {
1486 const [eventType, ...option] = event.split('_');
1487 const options = handleEventOptions(option);
1488 // Ref 函数
1489 if (isRef(value)) {
1490 const refVal = value;
1491 const refListener = watchRef(refVal, () => refVal.value
1492 ? (e) => {
1493 option.includes('prevent') && e.preventDefault();
1494 option.includes('stop') && e.stopPropagation();
1495 const callback = refVal.value;
1496 callback(e);
1497 }
1498 : undefined);
1499 // 设置事件监听
1500 refListener.value &&
1501 ele.addEventListener(eventType, refListener.value, options);
1502 // 监听事件变化
1503 watch(refListener, (newVal, oldVal) => {
1504 // 移除旧事件监听
1505 oldVal && ele.removeEventListener(eventType, oldVal);
1506 // 设置新事件监听
1507 newVal && ele.addEventListener(eventType, newVal, options);
1508 });
1509 return;
1510 }
1511 // 普通函数
1512 if (value instanceof Function) {
1513 // 设置事件监听
1514 ele.addEventListener(eventType, value, options);
1515 }
1516 }
1517 return;
1518 }
1519 // 特殊属性
1520 const specificAttrs = ['checked', 'selected', 'disabled', 'enabled'];
1521 // 特殊 key
1522 if (specificAttrs.includes(formatKey)) {
1523 // Ref
1524 if (isRef(value)) {
1525 const refVal = value;
1526 watchEffect(() => {
1527 if (refVal.value) {
1528 ele.setAttribute(formatKey, '');
1529 }
1530 else {
1531 ele.removeAttribute(formatKey);
1532 }
1533 });
1534 return;

Callers 1

handleAttributesFunction · 0.70

Calls 6

handleEventOptionsFunction · 0.70
isRefFunction · 0.70
watchRefFunction · 0.70
watchFunction · 0.70
watchEffectFunction · 0.70
subscribeFunction · 0.70

Tested by

no test coverage detected