Posted on 2007-03-16 09:19
dennis 閱讀(1895)
評(píng)論(0) 編輯 收藏 所屬分類:
web開發(fā)
??? 在W3C新的事件模型框架中,IE和Mozilla都實(shí)現(xiàn)了相應(yīng)的版本,IE的是attachEvent和detachEvent來(lái)實(shí)現(xiàn)元素事件的添加和刪除,而Mozilla則是標(biāo)準(zhǔn)的addEventListener和 removeEventListener。在傳統(tǒng)的javascript事件模型中,我們沒(méi)辦法為一個(gè)頁(yè)面元素注冊(cè)多個(gè)事件,只有靠自己來(lái)實(shí)現(xiàn)觀察者模式。代碼來(lái)自《ajax in action》,我添加了注釋
//命名空間
var?jsEvent?=?new?Array();
//構(gòu)造函數(shù)
jsEvent.EventRouter?=?function(el,eventType){
?//內(nèi)部維護(hù)一個(gè)事件列表
?this.lsnrs?=?new?Array();
?this.el?=?el;
?el.eventRouter?=?this;
?//注冊(cè)回調(diào)函數(shù)
?el[eventType]?=?jsEvent.EventRouter.callback;
};
//添加事件
jsEvent.EventRouter.prototype.addListener?=?function(lsnr){
?this.lsnrs.append(lsnr,true);?
}?;
//移除事件
jsEvent.EventRouter.prototype.removeListener=
function(lsnr){?
this.lsnrs.remove(lsnr);?
};?
//通知所有事件
jsEvent.EventRouter.prototype.notify?=?function(e){
?var?lsnrs?=?this.lsnrs;
?for(var?i=0;i<lsnrs.length;i++){
??var?lsnr?=?lsnrs[i];
??lsnr.call(this,e);
?}
};
//回調(diào)函數(shù)調(diào)用notify
jsEvent.EventRouter.callback=function(event){
?var?e?=?event?||?window.event;
?var?router?=?this.eventRouter;
?router.notify(e);
};
Array.prototype.append?=?function(obj,nodup){
?if(nodup){?
??this[this.length]=obj;
?}
};
Array.prototype.remove?=?function(o)
{
???var?i?=?this.indexOf(o);
???if?(i>-1)
??{
????this.splice(i,1);
???}
?????return?(i>-1);
???}??
};?
這里比較巧妙的就是
?el.eventRouter?=?this;//注冊(cè)回調(diào)函數(shù)
?el[eventType]?=?jsEvent.EventRouter.callback;
首先給el元素添加屬性eventRouter是當(dāng)前的EventRouter對(duì)象,然后,比如eventType假設(shè)為onclick,el是一個(gè)button元素,那么這里就是el[onclick]=jsEvent.EventRouter.callback;相當(dāng)于el.onclick=jsEvent.EventRouter.callback;
而請(qǐng)注意這個(gè)回調(diào)函數(shù)callback將首先得到元素的eventRouter對(duì)象,再調(diào)用此對(duì)象的notify方法觸發(fā)所有注冊(cè)的事件。
再請(qǐng)注意notify函數(shù)里面這一行:
?lsnr.call(this,e);
我們把event對(duì)象傳入此函數(shù)作參,而var?e?=?event?||?window.event;那么所有事件函數(shù)的第一個(gè)參數(shù)都將是event對(duì)象,避免了IE需要通過(guò)window.event得到的事件對(duì)象的瀏覽器不一致行為。
使用此對(duì)象方式:
var?mat=document.getElementById('mousemat');
cursor=document.getElementById('cursor');
var?mouseRouter=new?jsEvent.EventRouter(mat,"onmousemove");
mouseRouter.addListener(writeStatus);
mouseRouter.addListener(drawThumbnail);?