首先先看一下Typescript代码:

 

import template = require('art-template/lib/template-web');

interface TemplateBindConfig {
    el: string
    data: object
}


class TmpBind {

    el: string

    template: any

    data: object

    renderFn: any



    // 构造函数
    constructor(config:TemplateBindConfig) {
        // 绑定的容器id
        this.el = config.el;

        // 注入的数据
        this.data = config.data;

        this.renderFn = null
        var nodes=document.querySelector(config.el).children;
        var i=nodes.length;
        if(i>0){
            while(i--){
                if(nodes[i].tagName.toLowerCase()=="script" && nodes[i].getAttribute("type")=="text/html"){
                    // 模版id
                    this.template = nodes[i].innerHTML;
                    break;
                }
            }
        }

        this.render()
    }

    // 渲染模版
    render(data?): void {
        if (data) {
            this.data = data;
        }
        // 解析模版
        if(!this.renderFn){
            this.renderFn= template.compile(this.template);
        }

        const source = this.renderFn(this.data);
        // 更新容器的值
        document.querySelector(this.el).innerHTML = source;


    }


    setData(value: any): void {
        this.data=value;
        this.render();
    }

    // 重新设置模板
    setTemplate(value: any): void {
        this.template = value;
        this.renderFn= template.compile(value);
        this.render();
    }

    // 获取数据
    getData(): object {
        return this.data;
    }


}
View Code

相关文章:

  • 2021-08-14
  • 2022-12-23
  • 2021-06-26
  • 2022-12-23
  • 2021-09-28
  • 2021-12-31
  • 2021-11-01
猜你喜欢
  • 2021-08-31
  • 2022-12-23
  • 2022-12-23
  • 2021-06-24
  • 2021-05-14
相关资源
相似解决方案