在做事件绑定的时候要考虑浏览器的兼容性,每次绑定事件时都要去判断下当前浏览器是支持哪一种绑定方法,其实可以做到只判断一次。
实现事件绑定代码片段:
1) 首先创建绑定函数,确定必要参数。
bind: function(target, type, callback){
//实现逻辑...
}
2)创建兼容性绑定事件函数列表。
var methods = [
function(target, type, callback){ target.addEventListener(type, callback, false); },
function(target, type, callback){ target.attachEvent('on'+type, callback); }
];
主是要IE与非IE。
3)找到当前浏览器所支持的事件函数。
for(var i=0, len=methods.length; i<len; i++){
try{
methods[i](target, type, callback);
}catch(e){
continue;
}
this.bind = methods[i];
return methods[i];
}
这里有一点很重要,当找到合适的事件函数时,重置bind方法,这样就确保事件函数判断只会执行一次。
this.bind = methods[i];
删除事件也可以这样实现。
送上完整代码:
var Event = function(){};
Event.prototype = {
bind: function(target, type, callback){
var methods = [
function(target, type, callback){ target.addEventListener(type, callback, false); },
function(target, type, callback){ target.attachEvent('on'+type, callback); }
];
for(var i=0, len=methods.length; i<len; i++){
try{
methods[i](target, type, callback);
}catch(e){
continue;
}
this.bind = methods[i];
return methods[i];
}
},
unbind: function(target, type, callback){
var methods = [
function(target, type, callback){ target.removeEventListener(type, callback, false); },
function(target, type, callback){ target.dettachEvent('on'+type, callback); }
];
for(var i=0, len=methods.length; i<len; i++){
try{
methods[i](target, type, callback);
}catch(e){
continue;
}
this.bind = methods[i];
return methods[i];
}
}
}