在看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 };
View Code

相关文章:

  • 2022-12-23
  • 2021-06-01
  • 2022-12-23
  • 2021-08-31
  • 2021-10-29
  • 2021-07-06
  • 2022-12-23
  • 2021-09-25
猜你喜欢
  • 2022-02-23
  • 2021-10-17
  • 2022-12-23
  • 2021-06-16
  • 2021-07-26
  • 2021-12-15
  • 2022-12-23
相关资源
相似解决方案