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

先上代码

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 })();
原文地址:https://www.cnblogs.com/junwu/p/4917843.html