Dean Edwards大神写的addEvent库

直接晒代码:

 1 // written by Dean Edwards, 2005
 2 // with input from Tino Zijdel, Matthias Miller, Diego Perini
 3 
 4 // http://dean.edwards.name/weblog/2005/10/add-event/
 5 
 6 function addEvent(element, type, handler) {
 7     if (element.addEventListener) {
 8         element.addEventListener(type, handler, false);
 9     } else {
10         // assign each event handler a unique ID
11         if (!handler.$$guid) handler.$$guid = addEvent.guid++;
12         // create a hash table of event types for the element
13         if (!element.events) element.events = {};
14         // create a hash table of event handlers for each element/event pair
15         var handlers = element.events[type];
16         if (!handlers) {
17             handlers = element.events[type] = {};
18             // store the existing event handler (if there is one)
19             if (element["on" + type]) {
20                 handlers[0] = element["on" + type];
21             }
22         }
23         // store the event handler in the hash table
24         handlers[handler.$$guid] = handler;
25         // assign a global event handler to do all the work
26         element["on" + type] = handleEvent;
27     }
28 };
29 // a counter used to create unique IDs
30 addEvent.guid = 1;
31 
32 function removeEvent(element, type, handler) {
33     if (element.removeEventListener) {
34         element.removeEventListener(type, handler, false);
35     } else {
36         // delete the event handler from the hash table
37         if (element.events && element.events[type]) {
38             delete element.events[type][handler.$$guid];
39         }
40     }
41 };
42 
43 function handleEvent(event) {
44     var returnValue = true;
45     // grab the event object (IE uses a global event object)
46     event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
47     // get a reference to the hash table of event handlers
48     var handlers = this.events[event.type];
49     // execute each event handler
50     for (var i in handlers) {
51         this.$$handleEvent = handlers[i];
52         if (this.$$handleEvent(event) === false) {
53             returnValue = false;
54         }
55     }
56     return returnValue;
57 };
58 
59 function fixEvent(event) {
60     // add W3C standard event methods
61     event.preventDefault = fixEvent.preventDefault;
62     event.stopPropagation = fixEvent.stopPropagation;
63     return event;
64 };
65 fixEvent.preventDefault = function() {
66     this.returnValue = false;
67 };
68 fixEvent.stopPropagation = function() {
69     this.cancelBubble = true;
70 };

 

posted @ 2013-11-27 09:35  breezefeng  阅读(527)  评论(0编辑  收藏  举报