(一)原生JS实现 - 事件类方法
事件处理 - 添加事件
1 var addEventHandler = function (oTarget, sEventType, fnHandler) { 2 if (oTarget.addEventListener) { 3 oTarget.addEventListener(sEventType, fnHandler, false); 4 } else if (oTarget.attachEvent) { 5 oTarget.attachEvent("on" + sEventType, fnHandler); 6 } else { 7 oTarget["on" + sEventType] = fnHandler; 8 } 9 };
事件处理 - 移除事件
1 var removeEventHandler = function (oTarget, sEventType, fnHandler) { 2 if (oTarget.removeEventListener) { 3 oTarget.removeEventListener(sEventType, fnHandler, false); 4 } else if (oTarget.detachEvent) { 5 oTarget.detachEvent("on" + sEventType, fnHandler); 6 } else { 7 oTarget["on" + sEventType] = null; 8 } 9 };
事件处理 - Bind
1 var BindAsEventListener = function(object, fun) { 2 var args = Array.prototype.slice.call(arguments).slice(2); 3 return function(event) { 4 return fun.apply(object, [event || window.event].concat(args)); 5 } 6 };
使用:
1 var Test = function(){ 2 this.init(); 3 ); 4 Test.prototype = { 5 init:function(){ 6 this.name = ‘test‘; 7 this.btn = document.getElementById(‘test‘); 8 this._fC = BindAsEventListener(this, this._doClick,‘bind event‘); 9 addEventHandler(this.btn, "click", this._fC ); 10 }, 11 _doClick:funtion(e,str){ 12 e.preventDefault(); 13 alert(this.name + ‘ ‘ +str); 14 }, 15 destory:function(){ 16 removeEventHandler(this.btn, "click", this._fC ); 17 } 18 }
事件代理
1 var Delegate = function (parent,eventType, selector, fn , that){ 2 eventType = eventType || ‘click‘; 3 if(!parent){ 4 return; 5 } 6 if( typeof fn !== ‘function‘){ 7 return; 8 } 9 if( typeof selector !== ‘string‘){ 10 return; 11 } 12 var handle = function (e){ 13 var evt = window.event ? window.event : e; 14 var target = evt.target || evt.srcElement; 15 target = getDlgElement(target); 16 if(target){ 17 fn.call(that,{target:target,event:e}); 18 } 19 }; 20 var getDlgElement = function(ele){ 21 if(!ele){ 22 return null; 23 } 24 return ( (ele.id === selector) || 25 (ele.className && ele.className.indexOf(selector) != -1)) ? ele : getDlgElement(ele.parentNode); 26 }; 27 parent[‘on‘ + eventType] = handle; 28 };
使用:
1 var Test2 = function(){ 2 this.init(); 3 }; 4 Test2.prototype = { 5 init:function(){ 6 var me = this; 7 Delegate(document,‘click‘,‘classname‘,function(e){ 8 e.event.preventDefault(); 9 var obj = e.target; 10 me.setVaule(obj,‘test‘) 11 },this); 12 }, 13 setVaule:function(elem,str){ 14 elem.setAttribute(‘data-value‘,str); 15 } 16 }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。