在看Aaron的jquery源码解读时候,看到事件系统那块,作者提到了Dean Edwards的添加事件的设计,于是就点进去看了看。首先让我吃惊的是,代码非常少,寥寥几十行,非常简单。于是我就仔细的看了看(如果代码太多,可能就直接不看了)。
这段代码是Dean Edwards在2005年写的了,那时候还没有jquery。但是它的设计思路确实和jquery的事件系统有些相似,即便是在9年之后的今天。
于是把这段代码仔细研究,并在此跟大家分享以下。它将帮助你更好的理解jquery的事件系统。
先把源码粘上,:
1 function addEvent(element, type, handler) { 2 // assign each event handler a unique ID 3 if (!handler.$$guid) handler.$$guid = addEvent.guid++; 4 // create a hash table of event types for the element 5 if (!element.events) element.events = {}; 6 // create a hash table of event handlers for each element/event pair 7 var handlers = element.events[type]; 8 if (!handlers) { 9 handlers = element.events[type] = {}; 10 // store the existing event handler (if there is one) 11 if (element["on" + type]) { 12 handlers[0] = element["on" + type]; 13 } 14 } 15 // store the event handler in the hash table 16 handlers[handler.$$guid] = handler; 17 // assign a global event handler to do all the work 18 element["on" + type] = handleEvent; 19 }; 20 // a counter used to create unique IDs 21 addEvent.guid = 1; 22 23 function removeEvent(element, type, handler) { 24 // delete the event handler from the hash table 25 if (element.events && element.events[type]) { 26 delete element.events[type][handler.$$guid]; 27 } 28 }; 29 30 function handleEvent(event) { 31 // grab the event object (IE uses a global event object) 32 event = event || window.event; 33 // get a reference to the hash table of event handlers 34 var handlers = this.events[event.type]; 35 // execute each event handler 36 for (var i in handlers) { 37 this.$$handleEvent = handlers[i]; 38 this.$$handleEvent(event); 39 } 40 };