JavaScript命令模式原理与用法实例详解
本文实例讲述了JavaScript命令模式原理与用法。分享给大家供大家参考,具体如下:
第一,命令模式:
(1)用于消除调用者和接收者之间直接的耦合的模式,并且可以对(调用这个过程进行留痕操作)
(2)真的不要乱用这个模式,以为他使你简单调用写法变得非常的复杂和有些难以理解。
(3)你的业务出现了(回退操作)(重做操作)的需求的时候你就要考虑使用这个模式了。
命令的原理:
一种情况为发出者直接作用于执行者,这样耦合度很高,另外一种情况为,在发出者和执行者之间增加一个用存储命令的命令访问库也即命令命令模式。
第二,现在我们通过一个需求来学习该模式
需求为:
1.有一个"添加流程的按钮"单击的时候就会添加一个新的文本当做流程的描述
2.有"返回","重做"2个按钮来完成相应的任务。
第三,界面为
效果为,
根据上述图我们逐步完成
步骤一,定义主应用程序----接收者
functionmanager(){
this.addFlow=function(id,value){
//1.得到目标节点
vardiv=document.getElementById("div01");
varnewFlow=document.createElement("div");
newFlow.setAttribute("id",id);
newFlow.innerHTML=value;
div.appendChild(newFlow);
}
}
步骤二,为对象(执行者)建立命令访问库---意思是可以通过extcute方法访问到addFlow方法
manager.prototype.extcute=(function(){
/*command命令对象
**/
returnfunction(command){
returnthis[command.method](command.id,command.value);
}
})();
步骤三,初始化主类
varma=newmanager();//可以用该对象,调用其的东西 //用于存储"调用对象命令的"集合 varcommands=newArray(); //集合的游标--初始化在末尾 varindex=commands.length;
步骤四,客户端----发出者
varAPI=function(){
this.addFlow=function(){
//把调用封装起来
varcommand={
method:"addFlow",
id:newUUID().createUUID(),//产生id的插件
value:document.getElementById("flow").value
};
//把调用对象保存起来,用于回退和重做作用
commands.push(command);
//重新定位游标---赋值记录
index=commands.length;
//调用
ma.extcute(command);
};
/**
*用于返回的方法
*/
this.ret=function(){
if(index-1<0){
alert("已经到了最后一步了...");
}else{
varall=document.getElementById("div01").childNodes;
document.getElementById("div01").removeChild(all[all.length-1]);
index=index-1;
}
};
/**
*用于重做的方法
*/
this.again=function(){
if(index>=commands.length){
alert("已经到了最前面一步了,不能进行重做...");
}else{
varcommand=commands[index];//获取当前的命令位置
ma.extcute(command);
index=index+1;
}
}
}
步骤五,实例化客户端
API=newAPI();//实例化
这样html中的事件就可以起作用了。
在这里我们使用插件来让其功能支持自定义的键盘事件,插件名称为:keymaster.js
首先,如html中一样引入文件,
然后值调用key添加自定义的键盘事件
//添加支持ctrl+z--返回
key("ctrl+z",function(){
API.ret();
});
//重做---
key("ctrl+shift+x",function(){
API.again();
})
为此我们可以使用键盘的指定组合实现和鼠标点击一样的效果。
这里需要说明一下客户端的API中的id值,也是通过插件来动态生成的------插件名称为:uuid.js。这里附上源码
/*
uuid.js-Version0.2
JavaScriptClasstocreateaUUIDlikeidentifier
Copyright(C)2006-2008,ErikGiberti(AF-Design),Allrightsreserved.
Thisprogramisfreesoftware;youcanredistributeitand/ormodifyitunder
thetermsoftheGNUGeneralPublicLicenseaspublishedbytheFreeSoftware
Foundation;eitherversion2oftheLicense,or(atyouroption)anylater
version.
Thisprogramisdistributedinthehopethatitwillbeuseful,butWITHOUTANY
WARRANTY;withouteventheimpliedwarrantyofMERCHANTABILITYorFITNESSFORA
PARTICULARPURPOSE.SeetheGNUGeneralPublicLicenseformoredetails.
YoushouldhavereceivedacopyoftheGNUGeneralPublicLicensealongwith
thisprogram;ifnot,writetotheFreeSoftwareFoundation,Inc.,59Temple
Place,Suite330,Boston,MA02111-1307USA
Thelatestversionofthisfilecanbedownloadedfrom
http://www.af-design.com/resources/javascript_uuid.php
HISTORY:
6/5/06-InitialRelease
5/22/08-Updatedcodetorunfaster,removedrandrange(min,max)infavorof
asimplerrand(max)function.ReducedoverheadbyusinggetTime()
methodofdateclass(suggestionbyJamesHall).
KNOWNISSUES:
-StillnowaytogetMACaddressinJavaScript
-ResearchintootherversionsofUUIDshowpromisingpossibilities
(moreresearchneeded)
-Documentationneedsimprovement
*/
//OncreationofaUUIDobject,setit'sinitialvalue
functionUUID(){
this.id=this.createUUID();
}
//WhenaskedwhatthisObjectis,lieandreturnit'svalue
UUID.prototype.valueOf=function(){returnthis.id;}
UUID.prototype.toString=function(){returnthis.id;}
//
//INSTANCESPECIFICMETHODS
//
UUID.prototype.createUUID=function(){
//
//LooseinterpretationofthespecificationDCE1.1:RemoteProcedureCall
//describedathttp://www.opengroup.org/onlinepubs/009629399/apdxa.htm#tagtcjh_37
//sinceJavaScriptdoesn'tallowaccesstointernalsystems,thelast48bits
//ofthenodesectionismadeupusingaseriesofrandomnumbers(6octetslong).
//
vardg=newDate(1582,10,15,0,0,0,0);
vardc=newDate();
vart=dc.getTime()-dg.getTime();
varh='-';
vartl=UUID.getIntegerBits(t,0,31);
vartm=UUID.getIntegerBits(t,32,47);
varthv=UUID.getIntegerBits(t,48,59)+'1';//version1,securityversionis2
varcsar=UUID.getIntegerBits(UUID.rand(4095),0,7);
varcsl=UUID.getIntegerBits(UUID.rand(4095),0,7);
//sincedetectionofanythingaboutthemachine/browserisfartobuggy,
//includesomemorerandomnumbershere
//ifNICoranIPcanbeobtainedreliably,thatshouldbeputin
//hereinstead.
varn=UUID.getIntegerBits(UUID.rand(8191),0,7)+
UUID.getIntegerBits(UUID.rand(8191),8,15)+
UUID.getIntegerBits(UUID.rand(8191),0,7)+
UUID.getIntegerBits(UUID.rand(8191),8,15)+
UUID.getIntegerBits(UUID.rand(8191),0,15);//thislastnumberistwooctetslong
returntl+h+tm+h+thv+h+csar+csl+h+n;
}
//
//GENERALMETHODS(Notinstancespecific)
//
//Pulloutonlycertainbitsfromaverylargeinteger,usedtogetthetime
//codeinformationforthefirstpartofaUUID.Willreturnzero'sifthere
//aren'tenoughbitstoshiftwhereitneedsto.
UUID.getIntegerBits=function(val,start,end){
varbase16=UUID.returnBase(val,16);
varquadArray=newArray();
varquadString='';
vari=0;
for(i=0;i=base)varoutput=this.returnBase(MSD,base)+convert[LSD];
elsevaroutput=convert[MSD]+convert[LSD];
}
returnoutput;
}
//pickarandomnumberwithinarangeofnumbers
//intbrand(inta);where0<=b<=a
UUID.rand=function(max){
returnMath.floor(Math.random()*max);
}
//endofUUIDclassfile
感兴趣的朋友可以使用在线HTML/CSS/JavaScript前端代码调试运行工具:http://tools.jb51.net/code/WebCodeRun测试上述代码运行效果。
更多关于JavaScript相关内容还可查看本站专题:《javascript面向对象入门教程》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》
希望本文所述对大家JavaScript程序设计有所帮助。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。