寫給某人看的DOM事件傳遞模型

  • 用 fileset/legend 模擬 DOM structure
  • 用數字表示發生的順序
  • IE 使用者請下載支援 addEventListener / removeEventListener 的瀏覽器。(其實是我懶得寫支援 IE 的部份...)

http://jsfiddle.net/alivedise/bNqm6/

(function() {
    var count = 0;
    var phase = ['none', 'capture', 'at_target', 'bubble'];
    
    function eventHandler(evt) {
      document.querySelector('[name='+evt.currentTarget.id+']').innerHTML =  document.querySelector('[name='+evt.currentTarget.id+']').innerHTML + '<br/>' +
          + ++count + '.' + evt.currentTarget.id + ' caught the ball in phase: ' + phase[evt.eventPhase] + '.';
        
      if (document.getElementById('intercept').checked)
          evt.stopPropagation();
    }
    
    function clear() {
        var c = document.querySelectorAll('.caught');
        for (var i = 0, element; element = c[i]; i++) {
            element.textContent = '';
        }
        count = 0;
    }
    
    function unregisterEvents(capture) {
        document.getElementById('bug').removeEventListener('click', eventHandler, capture);
        document.getElementById('alive').removeEventListener('click', eventHandler, capture);
        document.getElementById('dolphin').removeEventListener('click', eventHandler, capture);
    }
    
    function registerEvents(capture) {
        document.getElementById('bug').addEventListener('click', eventHandler, capture);
        document.getElementById('alive').addEventListener('click', eventHandler, capture);
        document.getElementById('dolphin').addEventListener('click', eventHandler, capture);
    }
    
    document.getElementById('intercept').addEventListener('change', function() {
        clear();
    });
    
    document.getElementById('bubble').addEventListener('change', function() {
        clear();
        
        if (document.getElementById('bubble').checked) {
            unregisterEvents(true);
        } else {
            registerEvents(true);
        }
    });
    
    registerEvents(true);
    registerEvents(false);
}());

Comments

comments powered by Disqus