In the new event model framework, IE and Mozilla have implemented the corresponding version, IE is attachevent and detachevent to achieve the addition and deletion of element events, while Mozilla is the standard AddEventListener and RemoveEventListener. In the traditional JavaScript event model, we have no way to register multiple events for a page element, only to implement the observer pattern on our own. Code from Ajax in action, I added annotations
Name space
var jsevent = new Array ();
Constructors
Jsevent.eventrouter = function (El,eventtype) {
Internal maintenance of an event list
This.lsnrs = new Array ();
This.el = El;
El.eventrouter = this;
Registering callback Functions
El[eventtype] = JsEvent.EventRouter.callback;
};
Adding events
JsEvent.EventRouter.prototype.addListener = function (Lsnr) {
This.lsnrs.append (lsnr,true);
} ;
removing events
Jsevent.eventrouter.prototype.removelistener=
function (Lsnr) {
This.lsnrs.remove (Lsnr);
};
Notify All Events
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);
}
};
callback function call 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);
}
};
What's more ingenious here
El.eventrouter = this;
Registering callback Functions
El[eventtype] = JsEvent.EventRouter.callback;
First add attributes to El elements Eventrouter is the current Eventrouter object, and then, for example, EventType assumes that Onclick,el is a button element, then this is el[onclick]= JsEvent.EventRouter.callback; equivalent to El.onclick=jsevent.eventrouter.callback;
Note that this callback function callback first gets the Eventrouter object of the element, and then calls the Notify method of this object to trigger all registered events.
Again, notice the line in the Notify function:
Lsnr.call (this,e);
We passed the event object into this function as a parameter, while var e = Event | | Window.event; Then the first parameter of all event functions will be an event object, avoiding the browser inconsistency of the event object that IE needs to get through window.event.
Use this object way:
var mat=document.getElementById('mousemat');
cursor=document.getElementById('cursor');
var mouseRouter=new jsEvent.EventRouter(mat,"onmousemove");
mouseRouter.addListener(writeStatus);
mouseRouter.addListener(drawThumbnail);
Source: http://www.blogjava.net/killme2008/archive/2007/03/16/104150.html