基于“勿重复判断浏览器”的原则,将添加/删除/触发事件的三个分支重写。如下
var w3c = !!window.addEventListener, addListener = w3c ? function(el, type, fn) { el.addEventListener(type, fn, false); } : function(el, type, fn) { el.attachEvent('on' + type, fn); }, removeListener = w3c ? function(el, type, fn) { el.removeEventListener(type, fn, false); } : function(el, type, fn) { el.detachEvent('on' + type, fn); }; dispatch = w3c ? function(el, type){ try{ var evt = document.createEvent('Event'); evt.initEvent(type,true,true); el.dispatchEvent(evt); }catch(e){alert(e)}; } : function(el, type){ try{ el.fireEvent('on'+type); }catch(e){alert(e)} };
接口改为了on/un/fire
return { on : add, un : remove, fire : dispatch };