agile-ui
Version:
组件化的ui框架
131 lines (115 loc) • 4.45 kB
JavaScript
var util = module.exports = {
attributeHook(prop) {
const origin_getAttribute = prop.getAttribute;
const origin_setAttribute = prop.setAttribute;
const origin_hasAttribute = prop.hasAttribute;
const origin_removeAttribute = prop.removeAttribute;
const hook = {
__needHook(name) {
try{
const hookAttrs = this.$anestor.structure.hookAttrs || [];
return hookAttrs.indexOf(name) > -1;
} catch(e){
}
return false;
},
__setAttrValue(name, v){
const attr = this.__getAttr();
if(arguments.length>1) {
attr[name] = v || '';
} else {
delete attr[name];
}
if(origin_hasAttribute.call(this, name)) {
origin_removeAttribute.call(this, name);
}
this.attributeChangedCallback(name, attr[name] || '');
// $(this).trigger('change', attr[name] || '');
},
__getAttrValue(name){
const attr = this.__getAttr();
if(origin_hasAttribute.call(this, name)) {
const v = origin_getAttribute.call(this, name);
attr[name] = v;
origin_removeAttribute.call(this, name);
}
return attr[name] || '';
},
__getAttr(){
const name = '__attr_defined';
if(!this[name]) {
Object.defineProperty(this, name, {
value: {},
enumerable: false,
configurable: false
});
}
return this[name];
},
hasAttribute(name) {
const attr = this.__getAttr();
if(this.__needHook(name)) {
return attr.hasOwnProperty(name);
} else {
return origin_hasAttribute.apply(this, arguments);
}
},
removeAttribute(name) {
if(this.__needHook(name)) {
this.__setAttrValue(name);
} else {
return origin_removeAttribute.apply(this, arguments);
}
},
getAttribute(name) {
if(this.__needHook(name)) {
return this.__getAttrValue(name);
} else {
return origin_getAttribute.apply(this, arguments);
}
},
setAttribute(name, value) {
if(this.__needHook(name)) {
this.__setAttrValue(name, value);
} else {
origin_setAttribute.apply(this, arguments);
}
}
};
Object.assign(prop, hook);
},
getAnestor: function(anestor, el){
return (typeof anestor.getReplacement === 'function' ? anestor.getReplacement(el) : anestor.replacement ) || anestor;
},
insertAfter: function (newElement, targetElement) {
var parent = targetElement.parentNode;
if (parent.lastChild == targetElement) {
parent.appendChild(newElement);
} else {
parent.insertBefore(newElement, targetElement.nextSibling);
}
},
addChild: function ($child, jsDom) {
var $parent = $child.parentNode, $start = document.createComment(''), $end = document.createComment('');
$start.refer = $end.refer = jsDom;
$parent.insertBefore($start, $child);
util.insertAfter($end, $child);
jsDom.slotParent = $parent;
jsDom.slotPosition = {
start: $start,
end: $end
};
},
createComp: function (jsDom, template) {
const $fragment = document.createDocumentFragment();
Array.from(jsDom.childNodes).forEach(function ($child) {
$fragment.appendChild($child);
});
jsDom.innerHTML = template;
const $child = jsDom.querySelector('child');
if ($child) {
util.addChild($child, jsDom)
$child.parentNode.replaceChild($fragment, $child);
}
}
}