• 如何应用模板模式在现有的代码中


    先上代码

    var formatString = function(str,data){
    				return str.replace(/{#(w+)#}/g,function(match,key){
    					return typeof data[key] === undefined ?  '' : data[key]
    				});
    			}
    
    
    
    			self.each(function(){
    				_this = $(this);
    				//_html = '<div class="'+iset.iSelectBox+'"><div class="'+iset.iSelectCurrent+'" style="'+iset.width+'px">'+self.find('option:selected').text()+'</div><dl class="'+iset.iSelectOption+'" style="display:none; z-index:9999; '+iset.width+'px;">';
    				//模板模式start
    				var tpl = {
    					d : [
    						'<div class="{#iselectbox#}">',
    							'<div class="{#iselectcurrent#}" style="{#width#}px">',
    								'{#text#}',
    							'</div>',
    							'<dl class="{#iselectoption#}" style="display:none; z-index:9999; {#width#}px;">'
    
    					].join('')
    				}
    				var idata = {
    					iselectbox:iset.iSelectBox,
    					iselectcurrent:iset.iSelectCurrent,
    					iset.width,
    					text:self.find('option:selected').text(),
    					iselectoption:iset.iSelectOption
    				}
    				console.log(idata);
    				_html += formatString(tpl['d'],idata);
    				//模板模式end

     主要应用在字符串拼接的应用中,这样可以减少以前经常出现的拼接错误,格式比较清晰吧。

    示例二

     1 var viewCommand = (function(){
     2     var tpl = {
     3         product:[
     4             '<div>',
     5                 '<img src="{#src#}">',
     6                 '<p>{#text#}</p>',
     7             '</div>'
     8         ].join(''),
     9         title:[
    10             '<div class="title">',
    11                 '<div class="main">',
    12                     '<h2>[#title#]</h2>',
    13                     '<p>[#tips#]</p>',
    14                 '</div>',
    15             '</div>'
    16         ].join('')
    17     }
    18     var html = '';
    19 
    20     var formatString = function(str,data){
    21         return str.replace(/{#(w+)#}/g,function(match,key){
    22             return typeof data[key] === undefined ?  '' : data[key]
    23         });
    24     }
    25 
    26     var ss = formatString(tpl['product'],{src:'www.baidu.com',text:'aaaaa'});
    27     //alert(ss);
    28 
    29 
    30     //方法集合
    31     var Action = {
    32         create:function(){
    33 
    34         },
    35         display:function(){
    36 
    37         }
    38     }
    39     return function excute(){
    40 
    41     }
    42 
    43 })();
  • 相关阅读:
    get、put、post、delete含义与区别
    中奖数据表设计方案
    mysql递归
    java Ajax跨域请求COOKIE无法带上的解决办法
    tomcat 下配置ajax 跨域 tomcat font face 跨域 java跨域
    JAVA入门教程
    解决Navicat 出错:1130-host . is not allowed to connect to this MySql server,MySQL
    Hbuilder开发app时生成ios要的mobileprovision和p12文件步骤.
    js 获取浏览器高度和宽度值(多浏览器)
    Windows netstat 查看端口、进程占用 查看进程路径
  • 原文地址:https://www.cnblogs.com/junwu/p/4917843.html
Copyright © 2020-2023  润新知