MCPcopy Index your code
hub / github.com/Tencent/kbone / setAttribute

Method setAttribute

packages/miniprogram-render/src/node/element.js:966–1014  ·  view source on GitHub ↗
(name, value)

Source from the content-addressed store, hash-verified

964 }
965
966 setAttribute(name, value) {
967 if (typeof name !== 'string') return
968
969 // 保留对象/数组/布尔值/undefined 原始内容,方便处理小程序内置组件的使用
970 const valueType = typeof value
971 if (valueType !== 'object' && valueType !== 'boolean' && valueType !== 'function' && value !== undefined && !Array.isArray(value)) value = '' + value
972
973 if (name === 'kbone-attribute-map' || name === 'kbone-event-map') {
974 value = value || {}
975 if (typeof value === 'string') value = JSON.parse(value) // 确保存入的是对象
976 const oldValue = this.getAttribute(name)
977 const keys = Object.keys(value)
978 const oldKeys = oldValue ? Object.keys(oldValue) : null
979
980 if (name === 'kbone-attribute-map') {
981 // 特殊属性,用于批量设置属性
982 keys.forEach(key => this.setAttribute(key, value[key]))
983 if (oldKeys) {
984 oldKeys.forEach(key => {
985 if (!Object.prototype.hasOwnProperty.call(value, key)) this.removeAttribute(key)
986 })
987 }
988 } else {
989 // 特殊属性,用于批量监听事件
990 const window = cache.getWindow(this.$_pageId)
991
992 if (oldKeys) {
993 oldKeys.forEach(key => {
994 // 先删除所有旧的 handler
995 let handler = oldValue[key]
996 handler = typeof handler !== 'function' ? window[handler] : handler
997 this.removeEventListener(key, handler)
998 })
999 }
1000 keys.forEach(key => {
1001 let handler = value[key]
1002 handler = typeof handler !== 'function' ? window[handler] : handler
1003 this.addEventListener(key, handler)
1004 })
1005 }
1006 }
1007
1008 if (name === 'id') {
1009 // id 要提前到此处特殊处理
1010 this.id = value
1011 } else {
1012 this.$_attrs.set(name, value)
1013 }
1014 }
1015
1016 getAttribute(name) {
1017 if (typeof name !== 'string') return ''

Callers 15

$_initAttrsMethod · 0.95
setAttributeNSMethod · 0.95
element.test.jsFile · 0.45
image.test.jsFile · 0.45
transformWxComponent2DomFunction · 0.45
cloneNodeMethod · 0.45
input.test.jsFile · 0.45
switch.test.jsFile · 0.45
image.test.jsFile · 0.45
text.test.jsFile · 0.45
cover-view.test.jsFile · 0.45

Calls 6

getAttributeMethod · 0.95
removeAttributeMethod · 0.95
parseMethod · 0.45
removeEventListenerMethod · 0.45
addEventListenerMethod · 0.45
setMethod · 0.45

Tested by

no test coverage detected