特点:
1.支持fn参数中使用this关键字
2.相同fn绑定无效
缺点:
非ie下不能直接使用匿名函数直接当参数传递,这个谁有比较好的解决办法么?
CE.Event = {
handler : function(e){
e = e || window.event;
var _fn = "_" + e.type;
if(this[_fn]){
for(var _f in this[_fn]){
this[_fn][_f].call(this,e);
}
}
},
bind : function(obj, act, fn, capture){
if(window.addEventListener){
obj.addEventListener(act,fn,capture || false);
}else{
var _fn = "_" + act;
act = "on" + act;
if(!obj[_fn]){
obj[_fn] = [];
obj[act] = CE.Event.handler;
}else{
for(var _f in obj[_fn]){
if(obj[_fn][_f].toString() === fn.toString()){return};
}
}
obj[_fn][obj[_fn].length] = fn;
}
},
unbind : function(obj, act, fn, capture){
if(window.removeEventListener){
obj.removeEventListener(act,fn,capture || false);
}else{
var _fn = "_" + act;
if(obj[_fn]){
for(var _f in obj[_fn]){
if(obj[_fn][_f].toString() === fn.toString()){
try{
delete obj[_fn][_f];
}catch(e){
obj[_fn][_f] = null;
}
return;
}
}
}
}
}
};
提升了一下执行效率:
CE.Event = {
ecount : 1,
handler : function(e){
e = e || window.event;
if(this.evns[e.type]){
for(var evn in this.evns[e.type]){
this.evns[e.type][evn].call(this,e);
}
}
},
bind : function(obj, act, fn, capture){
if(window.addEventListener){
obj.addEventListener(act,fn,capture || false);
}else{
if(!fn.id){fn.id = CE.Event.ecount++};
if(!obj.evns){obj.evns = {}};
if(!obj.evns[act]){
obj.evns[act] = {};
if(obj["on" + act]){
obj.evns[act][0] = obj["on" + act];
}
}else{
for(var evn in obj.evns[act]){
if(evn.id === fn.id){return;}
}
}
obj.evns[act][fn.id] = fn;
obj["on" + act] = CE.Event.handler;
}
},
unbind : function(obj, act, fn, capture){
if(window.removeEventListener){
obj.removeEventListener(act,fn,capture || false);
}else{
if(obj.evns && obj.evns[act]){
try{
delete obj.evns[act][fn.id];
}catch(e){
obj.evns.act[fn.id] = null;
}
return;
}
}
}
};
posted on 2010-01-14 01:17
jacklau 阅读(218)
评论(1) 编辑 收藏