一个关于样式管理器的 Styled 对象!~~

发布时间 2023-03-27 11:19:01作者: blurs
const Styled = function(dom, styled, datas, isOnlyXid){
        this.xid = isOnlyXid || getXid();    
        this.dom = dom;
        this.dom.classList.add(this.xid);
        this.styled = styled.replace(/\t|\n/g,"");
        this.datas = datas;
        
        this.styleElement = this.createStyle();
        this.render();
    }
    
    Styled.prototype = {
            
        // 生成唯一识别码
        createStyle (){
            const o = document.head.querySelector("."+this.xid);
            if( o ){ 
                return o;
            }
            
            const style = document.createElement("style");
            document.head.appendChild(style);
            style.classList.add(this.xid);
            return style;
        },
        
        setDatas(opt) {
            this.datas = Object.assign(this.datas, opt);
            this.render();
        },
        
        render (){
            // this.styleElement.innerHTML = eval(`()=>{ var {${Object.keys(this.datas)}} = this.datas, xid=${this.xid}; return {} }()`);
            this.styleElement.innerHTML = function(){ 
                eval(`var {${Object.keys(this.datas)}} = this.datas, xid="${this.xid}"`); 
                return eval("\`"+this.styled+"\`");
            }.call(this);
        }
    }