事件处理 - 添加事件
var addEventHandler = function (oTarget, sEventType, fnHandler) {
if (oTarget.addEventListener) {
oTarget.addEventListener(sEventType, fnHandler, false);
} else if (oTarget.attachEvent) {
oTarget.attachEvent("on" + sEventType, fnHandler);
} else {
oTarget["on" + sEventType] = fnHandler;
}
};
事件处理 - 移除事件
var removeEventHandler = function (oTarget, sEventType, fnHandler) {
if (oTarget.removeEventListener) {
oTarget.removeEventListener(sEventType, fnHandler, false);
} else if (oTarget.detachEvent) {
oTarget.detachEvent("on" + sEventType, fnHandler);
} else {
oTarget["on" + sEventType] = null;
}
};
事件处理 - Bind
var BindAsEventListener = function(object, fun) {
var args = Array.prototype.slice.call(arguments).slice(2);
return function(event) {
return fun.apply(object, [event || window.event].concat(args));
}
};
使用:
var Test = function(){
this.init();
);
Test.prototype = {
init:function(){
this.name = 'test';
this.btn = document.getElementById('test');
this._fC = BindAsEventListener(this, this._doClick,'bind event');
addEventHandler(this.btn, "click", this._fC );
},
_doClick:funtion(e,str){
e.preventDefault();
alert(this.name + ' ' +str);
},
destory:function(){
removeEventHandler(this.btn, "click", this._fC );
}
}
事件代理
var Delegate = function (parent,eventType, selector, fn , that){
eventType = eventType || 'click';
if(!parent){
return;
}
if( typeof fn !== 'function'){
return;
}
if( typeof selector !== 'string'){
return;
}
var handle = function (e){
var evt = window.event ? window.event : e;
var target = evt.target || evt.srcElement;
target = getDlgElement(target);
if(target){
fn.call(that,{target:target,event:e});
}
};
var getDlgElement = function(ele){
if(!ele){
return null;
}
return ( (ele.id === selector) ||
(ele.className && ele.className.indexOf(selector) != -1)) ? ele : getDlgElement(ele.parentNode);
};
parent['on' + eventType] = handle;
};
使用:
var Test2 = function(){
this.init();
};
Test2.prototype = {
init:function(){
var me = this;
Delegate(document,'click','classname',function(e){
e.event.preventDefault();
var obj = e.target;
me.setVaule(obj,'test')
},this);
},
setVaule:function(elem,str){
elem.setAttribute('data-value',str);
}
}