将请求与具体的实现解耦,并封装成独立对象,从而使不同的请求对客户端的实现参数化,这就是命令模式。
1、代码实现
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<meta charset="utf-8">
<style>
#containers div {
margin-right: 5px;
border:solid 1px blue;
padding: 5px;
float: left;
}
</style>
</head>
<body>
<span id="container"></span>
<div id="containers"></div>
<script type="text/javascript">
var viewCommand = (function(){
var tpl = {
product:[
'<div>','<h3>{#subtitle#}</h3>','<p>{#text#}</p>','</div>'
].join(''),
title:[
'<div class="title">','<div class="main">','<h2>{#title#}</h2>','<p>{#tips#}</p>','</div>','</div>'
].join('')
},
html = '';//缓存字符串
//格式化字符串
function formatString(str,obj){
return str.replace(/\{#(\w+)#\}/g,function(match,key){
return obj[key];
})
}
var Action = {
create:function(data,view){
if(data.length){
for(var i=0,len=data.length;i<len;i++){
html += formatString(tpl[view],data[i]);
}
} else html += formatString(tpl[view],data);
},
display:function(container,data,view){
if(data){
this.create(data,view);
}
document.getElementById(container).innerHTML = html;
html = '';
}
}
return function execute(msg){
msg.param = Object.prototype.toString.call(msg.param) === "[object Array]"?msg.param : [msg.param];
Action[msg.command].apply(Action,msg.param);
}
})();
//测试一下
var productData = [
{
subtitle:"subtitle1",
text:"Text1"
},
{
subtitle:"subtitle2",
text:"Text2"
},
{
subtitle:"subtitle3",
text:"Text3"
}
],
titleData = {
title:"我是大标题",
tips:"发表时间:"+new Date()
};
//创建一个title
viewCommand({
command:'display',
param:['container',titleData,'title']
});
//单独创建一个
viewCommand({
command:'create',
param:[{
subtitle:"我是单独创建的",
text:"单独创建的标题"
},'product']
});
//创建多个
viewCommand({
command:'display',
param:['containers',productData,'product']
});
</script>
</body>
</html>
2、运行效果