JavaScriptイベントバインド方法


簡易実用版:
function bind(elm, evType, fn, useCapture) {
 if (elm.addEventListener) {
  elm.addEventListener(evType, fn, useCapture);//DOM2.0
  return true;
 }else if (elm.attachEvent) {
  var r = elm.attachEvent('on' + evType, fn);//IE5+
  return r;
 }else {
  elm['on' + evType] = fn;//DOM 0
 }
}

 
Dean Edwards版:機能は非常に強く、IEのthis指向の問題を解決し、eventはいつも最初のパラメータとして伝わり、ブラウザをまたいではなおさらだ.
function bind(element, type, handler) {
 //                 ID
 if (!handler.$$guid) handler.$$guid = addEvent.guid++;
 //               
 if (!element.events) element.events = {};
 //    "  /  "               
 var handlers = element.events[type];
 if (!handlers) {
  handlers = element.events[type] = {};
  //           (   )
  if (element["on" + type]) {
   handlers[0] = element["on" + type];
  }
 }
 //            
 handlers[handler.$$guid] = handler;
 //                    
 element["on" + type] = handleEvent;
};
//       ID    
addEvent.guid = 1;
function removeEvent(element, type, handler) {
 //             
 if (element.events && element.events[type]) {
  delete element.events[type][handler.$$guid];
 }
};
function handleEvent(event) {
 var returnValue = true;
 //      (IE        )
 event = event || fixEvent(window.event);
 //               
 var handlers = this.events[event.type];
 //         
 for (var i in handlers) {
  this.$$handleEvent = handlers[i];
  if (this.$$handleEvent(event) === false) {
   returnValue = false;
  }
 }
 return returnValue;
};
// IE         “   ”  
function fixEvent(event) {
 //     W3C  
 event.preventDefault = fixEvent.preventDefault;
 event.stopPropagation = fixEvent.stopPropagation;
 return event;
};
fixEvent.preventDefault = function() {
 this.returnValue = false;
};
fixEvent.stopPropagation = function() {
 this.cancelBubble = true;
};


 
HTML 5版:
var addEvent=(function(){
 if(document.addEventListener){
  return function(el,type,fn){
   if(el.length){
    for(var i=0;i<el.length;i++){
     addEvent(el[i],type,fn);
    }
   }else{
    el.addEventListener(type,fn,false);
   }
  };
 }else{
  return function(el,type,fn){
   if(el.length){
    for(var i=0;i<el.length;i++){
     addEvent(el[i],type,fn);
    }
   }else{
    el.attachEvent(‘on‘+type,function(){
     return fn.call(el,window.event);
    });
   }
  };
 }
})();