16.模板模式

148 阅读1分钟
function Alert(data) {
        if(!data) { this.data = '' }
        this.container = document.createElement('div')
        this.title = document.createElement('p')
        this.close = document.createElement('button')
        this.confirm = document.createElement('button')
        this.title.innerHTML = data
        this.close.innerHTML = 'close'
        this.confirm.innerHTML = 'confirm'
    }
    Alert.prototype = {
        init: function() {
            this.container.appendChild(this.title)
            this.container.appendChild(this.close)
            this.container.appendChild(this.confirm)
            document.body.appendChild(this.container)
            this.btnMethods()
        },
        btnMethods: function() {
            let that = this
            this.close.onclick = function() {
                console.log('close');
                that.hide()
            }
            this.confirm.onclick = function() {
                console.log('confirm');
                that.show()
            }
        },
        show: function() {
            this.container.style = 'display: bloack'
        },
        hide: function() {
            this.container.style = 'display: none'
        }
    }
    let a1 = new Alert('aaaaaaaa')
    a1.init()
    let a2 = new Alert('bbbbbbbbbb')
    a2.init()

    function BigAlert(data, title) {
        Alert.call(this,data)
        this.bigtitle = document.createElement('h1')
        this.bigtitle.innerHTML = title
    }
    BigAlert.prototype = new Alert()
    let b1 = new BigAlert('ccccc', 'bigbigbig')
    b1.container.appendChild(b1.bigtitle)
    b1.init()

    function forMatterStr(str, data) {
        return str.replace(/\{#(\w+)#\}/g, function(match, key){
            console.log(match, key)
            return typeof(data[key]) == undefined ? '' : data[key]
        })
    }
    // /\{#\w+#\}/g
    let res = forMatterStr('<a href="{#href#}" title="{#title#}">"{#name#}"</a>', {href:'bbb', title:'title', name: 'wawa'})
    console.log(res)

    function Nav(data) {
        this.item = '<a href="{#href#}" title="{#title#}">"{#name#}"</a>'
        this.html = document.createElement('div')
        // data.forEach((index) => {
        //     this.html += forMatterStr(this.item, data[index])
        // })
        for (let index = 0; index < data.length; index++) {
            const element = data[index];
            this.html += forMatterStr(this.item, data[index])
        }
        return this.html
    }
    function NumNav(data) {
        var tpl = '<b>{#num#}</b>'
        for (let index = 0; index < data.length; index++) {
            const element = data[index];
            data[index].name += data[index].name + forMatterStr(tpl, data[index])
        }
        return Nav.call(this, data)
    } 
    var nav = document.createElement('div')
    nav.innerHTML = NumNav([{href: 'www', title: 'ttt', name:'aaa', num:'1'}])
    document.body.appendChild(nav)