JavaScript设计模式(七):架构型设计模式-Widget模式

分而治之-Widget模式

Widget(Web Widget指的是一块可以在任意页面中执行的代码块)

Widget模式是指借用Web Widget思想将页面分解成部件,针对部件开发,最终组合成完整的页面。

art-templateejs

art-template: http://aui.github.io/art-template/zh-cn/

ejs: https://ejs.bootcss.com/#promo

在这里插入图片描述

<!-- art-template -->
<div id="test"></div>
<script id="tpl-user" type="text/html">
    <label>标准语法: </label>
    {
      
      {
      
      if user}}
        <span>{
      
      {
      
      user.name}}</span>
    {
      
      {
      
      /if}}
    <hr>
    <label>原始语法: </label>
    <% if (user) {
      
       %>
        <span><%= user.name %></span>
    <% } %>
</script>

    <!-- 
        // 原始语法的界定符规则
        template.defaults.rules[0].test = /<%(#?)((?:==|=#|[=-])?)[ \t]*([\w\W]*?)[ \t]*(-?)%>/;

        // 标准语法的界定符规则
        template.defaults.rules[1].test = /{
    
    {([@#]?)[ \t]*(\/?)([\w\W]*?)[ \t]*}}/; 
    -->

<!-- https://unpkg.com/[email protected]/lib/template-web.js -->
<script src="./template-web.js"></script>
<script>
    const source = document.getElementById('tpl-user').innerHTML;
    var html = template.render(source, {
      
      
        user: {
      
      
            name: 'Lee'
        }
    });
    console.log(html);
    document.getElementById('test').innerHTML = html;
</script>

Widget模式

在这里插入图片描述

<style>
    span {
      
      
        padding: 0 5px;
        color: cornflowerblue;
    }

    span.selected {
      
      
        color: red;
    }
</style>

<body>
    <div id="demo"></div>
    <script src="./index.js"></script>
</body>
~(function (template) {
    
    
    /**
     * 处理模板
     *  处理结果示例:
     *      tpl_list.push('<div>');
     *      for (var i = 0; i < list.length; i++) {
     *          tpl_list.push('<span class="tag_item ');
     *          if (list[i]['is_selected']) {
     *              tpl_list.push(' selected ');
     *          }
     *          tpl_list.push(
     *              '" title="',
     *              typeof (list[i]['title']) === 'undefined' ? '' : list[i]['title'],
     *              '">',
     *              typeof (list[i]["text"]) === 'undefined' ? '' : list[i]["text"],
     *              '</span>'
     *          );
     *      }
     *      tpl_list.push('</div>');
     * @param {string} source 模板
     */
    function dealTpl(source) {
    
    
        let [left, right] = ['{%', '%}'];
        let str = source
            // 转义标签内的< 如:<div>{%if(a&lt;b)%}</div> -> <div>{%if(a<b)%}</div>
            .replace(/&lt;/g, '<')
            // 转义标签内的>
            .replace(/&gt;/g, '>')
            // 过滤回车符,制表符,回车符
            .replace(/[\r\t\n]/g, '')
            // 替换内容
            .replace(new RegExp(`${
      
      left}=(.*?)${
      
      right}`, 'g'), `', typeof($1) === 'undefined' ? '' : $1,'`)
            // 替换左分隔符
            .replace(new RegExp(left, 'g'), `');`)
            // 替换右分隔符
            .replace(new RegExp(right, 'g'), `tpl_list.push('`);
        return `tpl_list.push('${
      
      str}');`
    }


    /**
     * 编译模板为字符串
     * @param {string} source 模板
     * @param {any} data 数据
     * @returns 编译好的html文本
     */
    template.compile = function (source, data) {
    
    

        let str = dealTpl(source);

        /**
         * fnBody目标逻辑
         */
        // let tpl_list = [];
        // // 闭包,模板容器组添加成员
        // let fn = (function (data) {
    
    
        //      
        //     // ==============【START】 由eval(tpl_key)生成 ====================
        //     var list = data['list'];
        //     // ==============【END】 由eval(tpl_key)生成 ====================
        // 
        //     // ==============【START】 由dealTpl函数生成 ====================
        //     tpl_list.push('<div>');
        //     for (var i = 0; i < list.length; i++) {
    
    
        //         tpl_list.push('<span class="tag_item ');
        //         if (list[i]['is_selected']) {
    
    
        //             tpl_list.push(' selected ');
        //         }
        //         tpl_list.push(
        //             '" title="',
        //             typeof (list[i]['title']) === 'undefined' ? '' : list[i]['title'],
        //             '">',
        //             typeof (list[i]["text"]) === 'undefined' ? '' : list[i]["text"],
        //             '</span>'
        //         );
        //     }
        //     tpl_list.push('</div>');
        //     // ==============【END】 由dealTpl函数生成 ====================
        //
        // }(data));
        // fn = null; // 释放闭包
        // return tpl_list.join('');

        const fnBody = `
            let tpl_list = [];

            // 闭包,模板容器组添加成员
            let fn = (function (data) {

                // 渲染数据变量的执行函数体
                let tpl_key = ''; // 目标 ---> var list = data['list'];

                Object.keys(data).forEach(key => {
                    tpl_key += ('var ' + key + ' = data["' + key + '"];');
                });

                // 执行渲染数据变量函数
                eval(tpl_key);
                
                ${
      
      str}

            }(tplData));

            fn = null; // 释放闭包

            return tpl_list.join('');
        `;

        return new Function('tplData', fnBody)(data);
    };


}((function () {
    
    
    return window.template = {
    
    };
}())));
// 自定义模板。语法使用{% xxx %};属性值使用{%= xxx %}
var source =
    `<div>
        <p>{%= userInfo.name %}</p>
        {% for (var i = 0; i < list.length; i++) { %} 
            <span class="tag_item {% if (list[i]['is_selected']) { %} selected {% } %}" 
                title="{%= list[i]['title'] %}">
                {%= list[i]["text"] %}
            </span>
        {% } %}
    </div>`;

var data = {
    
    
    userInfo: {
    
    
        name: 'Lee'
    },
    list: [
        {
    
     is_selected: 1, title: '这是一本设计模式书', text: '设计模式' },
        {
    
     is_selected: 0, title: '这是一本HTML书', text: 'HTML' },
        {
    
     is_selected: 0, title: '这是一本CSS书', text: 'CSS' },
        {
    
     is_selected: 0, title: '这是一本JavaScript书', text: 'JavaScript' },
    ]
};

document.getElementById('demo').innerHTML = template.compile(source, data);

猜你喜欢

转载自blog.csdn.net/weixin_43526371/article/details/127845461
今日推荐