WEB开发网      婵犻潧鍊婚弲顐︽偟椤栨稓闄勯柦妯侯槸閻庤霉濠婂骸浜剧紒杈ㄥ笚閹峰懘鎮╅崹顐ゆ殸婵炴垶鎸撮崑鎾趁归悩鐑橆棄闁搞劌瀛╃粋宥夘敃閿濆柊锕傛煙鐎涙ê鐏f繝濠冨灴閹啴宕熼鍡╀紘婵炲濮惧Λ鍕叏閳哄懎绀夋繛鎴濈-楠炪垽鎮归崶褍妲婚柛銊ュ缁傚秹鏁撻敓锟� ---闂佹寧娲╅幏锟�
开发学院网页设计JavaScript Javascript乱弹设计模式系列(5) - 命令模式(Comm... 阅读

Javascript乱弹设计模式系列(5) - 命令模式(Command)

 2010-09-14 13:38:52 来源:WEB开发网 闂侀潧妫撮幏锟�闂佸憡鍨电换鎰版儍椤掑倵鍋撳☉娆嶄沪缂傚稄鎷�婵犫拃鍛粶闁靛洤娲ㄩ埀顒佺⊕閵囩偟绱為敓锟�闂侀潧妫撮幏锟�  闂佺ǹ绻楀▍鏇㈠极閻愭娑樷枎閹邦剛娉氶梺鍛婎殔濞层劌鈻撻幋婵愬殫妞ゆ梻鍘х憴锟�
核心提示: Menu继承于MenuComponent接口(var MenuComponent = new Interface("MenuComponent", [["getElement"]]);),并且在上一篇组合模式讲过,Javascript乱弹设计模式系列

Menu继承于MenuComponent接口(var MenuComponent = new Interface("MenuComponent", [["getElement"]]);),并且在上一篇组合模式讲过,它作为Composite复合元素。

MenuItem的实现如下:

functionMenuItem(text,title,href,command){
  this.text=text;
  this.title=title;
  this.href=href;
  this.command=command;
  Interface.registerImplements(this,MenuComponent);
}
MenuItem.prototype={
  getElement:function(){
    varliElement=document.createElement("li");
    liElement.className="Menu-Leaf";
    liElement.title=this.title;
    varanchor=document.createElement("a");
    anchor.href=this.href;
    liElement.appendChild(anchor);
    anchor.innerHTML=this.text;
    varcommand=this.command;
    addEvent(anchor,"click",function(){
      command.execute();
    });
    returnliElement;
  }
}

其中参数command是作为传递进来的“命令对象”,比如前面的onBoldCommand的“加粗”命令对象,并且通过方法getElement()实现菜单按钮的点击触发达到命令对象的触发请求,而MenuItem不需要知道命令对象的具体实现;

    addEvent(anchor, "click", function(){
      command.execute();
    });

通过这句代码来添加点击事件从而执行命令对象的实现;

上一页  1 2 3 4 5 6  下一页

Tags:Javascript 乱弹 设计模式

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接