1. 程式人生 > >Dean Edwards大牛,addEvent簡簡單單幾十行程式碼體現基礎之紮實

Dean Edwards大牛,addEvent簡簡單單幾十行程式碼體現基礎之紮實

function addEvent(element, type, handler) {
    // assign each event handler a unique ID
    // element繫結的物件 type 事件的型別(click)  handler回撥函式<span style="white-space:pre">
</span>    //<span style="white-space:pre">	</span>addEvent.guid在該函式下面有初始化為  1
   //  分配一個不重複的ID
    if (!handler.$$guid) handler.$$guid = addEvent.guid++;
    // create a hash table of event types for the element
    //<span style="white-space:pre">	</span>如果該元素之前沒有被繫結,則初始化為一個key/value鍵值對的物件/儲存handler
    if (!element.events) element.events = {};
    // create a hash table of event handlers for each element/event pair
    var handlers = element.events[type];<span style="white-space:pre">	</span>//<span style="white-space:pre">	</span>{}/空物件   handlers引用element.events[type]物件
   
    if (!handlers) {
        handlers = element.events[type] = {};  // 
        // store the existing event handler (if there is one)
        if (element["on" + type]) {<span style="white-space:pre">	</span>//  如果元素之前繫結過type型別的時間,以0為鍵值,value為繫結過的回撥
            handlers[0] = element["on" + type];
        }
    }
    // store the event handler in the hash table
    // {'0':func1,'1':func2...}
    handlers[handler.$$guid] = handler;<span style="white-space:pre">	</span>//<span style="white-space:pre">	</span>將這次的繫結增加到handlers物件中,
    // assign a global event handler to do all the work
    element["on" + type] = handleEvent; //      最後將handleEvent繫結到elementDOM上
    
};
// a counter used to create unique IDs
addEvent.guid = 1;

//<span style="white-space:pre">	</span>解綁沒什麼,就是clear繫結的事件
function removeEvent(element, type, handler) {
    // delete the event handler from the hash table
    if (element.events && element.events[type]) {
        delete element.events[type][handler.$$guid];
    }
};

function handleEvent(event) {
    // grab the event object (IE uses a global event object)
    event = event || window.event;
    // get a reference to the hash table of event handlers
    var handlers = this.events[event.type];
    // execute each event handler
    for (var i in handlers) {
       // 取出當前型別的時間的回撥函式陣列,並一一執行
       // 注意這裡的this,為什麼這樣寫,而不寫handlers[i](),稍後總結講
        this.$$handleEvent = handlers[i];
        this.$$handleEvent(event);
    }
};

 二 :優點